源程序:
#include <iostream>
using namespace std;
class Sample
{
private:
int x;
public:
Sample() {}
Sample(int a)
{
x = a;
}
void disp()
{
cout << "x=" << x << endl;
}
Sample operator+(Sample& s2);
};
Sample Sample::operator+(Sample& s2)
{
return Sample(this->x+s2.x);
}
int main()
{
Sample obj1(10);
Sample obj2(20);
Sample obj3;
obj3 = obj1 + obj2;
obj3.disp();
return 1;
}
运行结果: