#include<iostream> using namespace std; class Complex{ public: Complex(double r=0.0,double i=0.0):real(r),imag(i){} Complex operator + (const Complex &c2) const; Complex operator - (const Complex &c2) const; void display() const; private: double real,imag; }; void Complex::display() const{ cout<<"("<<real<<","<<imag<<")"<<endl; } Complex Complex::operator + (const Complex &c2) const{ return Complex(real+c2.real,imag+c2.imag);//调用Complex构造函数创建一个临时对象并返回它 //Complex c(real+c2.real,imag+c2.imag); //return c; } Complex Complex::operator - (const Complex &c2) const{ return Complex(real-c2.real,imag-c2.imag); } int main(){ Complex c1(5,4),c2(2,10),c3; cout<<"c1=";c1.display(); cout<<"c2=";c2.display(); c3=c1-c2; cout<<"c2=c1-c2=";c3.display(); c3=c1+c2; cout<<"c2=c1+c2=";c3.display(); return 0; }
时间: 2024-10-09 07:31:03