定义计数器 Counter 类,对其重载运算符 + 。
Counter.h: class Counter{ private: double x; public: Counter(){x=0.0;} Counter(double x1):x(x1){}; Counter operator +(Counter c){ return Counter(x+c.x); }; double getX(){return x;}; }; Main.cpp: #include<iostream> (720)#include"Counter.h" using namespace std; int main(){ double x,y; cout<<"input x:"<<endl; cin>>x; cout<<"input y:"<<endl; cin>>y; Counter x1(x); Counter y1(y); Counter count=x1+y1; cout<<"Add Count:"<<count.getX()<<endl; return 0; }输出结果:
解:
源程序:
程序运行输出:
varOne: 2
varTwo: 4
varThree: 6