编写一个计数器Counter类,对其重载运算符+。对运算符有点不太懂,麻烦哪位高手指点一下!!!!!!
不知道你是要一元的还是二元的
以下是一元的:
#include <iostream>
using namespace std;
class Counter
{
int i;
public:
Counter(int ii = 0) : i(ii) {}
friend const Counter operator+(const Counter & cc);
};
const Counter operator+(const Counter & cc)
{
cout<<"+Counter\n";
return cc;
}
int main()
{
Counter c;
+c;
system("pause");
return 0;
}
以下是二元的:
#include <iostream>
using namespace std;
class Counter
{
int i;
public:
Counter( int ii =0) : i(ii) {}
friend const Counter operator+(const Counter & c,const Counter & cc);
void print()
{
cout<<"i = "<<i<<endl;
}
};
const Counter operator+(const Counter & c,const Counter & cc)
{
return Counter(c.i + cc.i);
}
int main()
{
Counter c1(1),c2(2);
Counter c3 = c1 +c2;
c3.print();
system("pause");
return 0;
}