运算符的重载
发布网友
发布时间:2022-05-23 19:54
我来回答
共1个回答
热心网友
时间:2023-11-19 01:34
class Complex
{
private:
double real;//实部
double imag;//虚部
public:
Complex(double r=0.0,double i=0.0):real(r),imag(i){}//构造函数
Complex operator+(const Complex &rc) const;//重载+
Complex& operator=(const Complex &rc);//重载=
void display();//显示复数
};
Complex Complex::operator+(const Complex &rc) const
{
return Complex(this->real+rc.real,this->imag+rc.imag);
}
Complex& Complex::operator=(const Complex &rc)
{
real=rc.real;imag=rc.imag;
return *this;
}
void Complex::display()
{
cout<<real<<'+'<<imag<<'i'<<endl;
}
int main()
{
Complex c1(10,20),c2,c3;
c1.display();
c2.display();
c3.display();
c3=c2=c1;
c2.display();
c3.display();
c3=c1+c2;
c3.display();
}