随便一个简单代码:
#include <iostream>
#include <string>
using namespace std;
class Complex
{
double real,imag;
public:
Complex(double r,double i):real(r),imag(i){}
void display(const string &name)
{cout << name << real << "," << imag << "i" << endl;}
friend Complex& operator+(Complex &c1,Complex &c2);
};
Complex& operator+(Complex &c1,Complex &c2)
{
Complex c;
c.real = c1.real + c2.real;
c.imag = c1.imag + c2.imag;
return c;
}
int main()
{
Complex c1(1,1),c2(2,2),c3;
c3 = c1 + c2;
c3 = c3 + c1; //为何这两行不能写成c3=c1+c2+c1?
c3.display("c3 = ");
system("pause"); return 0;
}