#include <iostream> using namespace std; class complex{ private: int real,imag; public: complex(int r=0,int i=0):real(r),imag(i){} friend complex operator +(complex c1); friend complex operator -(complex c1); void diplay(); }; void complex::diplay(){cout < <"real:" < <real < <"imag:" < <imag < <endl;}
complex operator +(complex c1){ return complex(real+c1.real, imag+c1.imag); } complex operator -(complex c1){ return complex(real-c1.real,imag-c1.imag); } int main(){ complex c1(1,2),c2(2,3),c3; c1.diplay(); c2.diplay(); c3=c1+c2; c3.diplay(); c3=c1-c2; c3.diplay(); } //此处不能通过,没想通,面下面这个就可以运行,不知为什么? #include <iostream> using namespace std; class complex{ private: int real,imag; public: complex(int r,int i); void display(); friend complex operator +(complex c1,complex c2); friend complex operator -(complex c1,complex c2); }; complex::complex(int r,int i){ real=r; imag=i; } complex complex::operator +(complex c1,complex c2){ return complex(c1.real+c2.real,c1.imag+c2.imag); } complex complex::operator -(complex c1,complex c2){ return complex(c1.real-c2.real,c1.imag-c2.imag); } void complex::display(){ cout < <"real=" < <real < <"imag=" < <imag < <endl; } int main(){
}
|