#include<iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real = 0;
imag = 0;
}
Complex(double r,double i)
{
real = r;
imag = i;
}
void display()
{
cout << "(" << real << "," << imag << "i" << ")" << endl;
}
operator double()//使double类型的数据能与复数相加
{
return real;
}
//实现交换律
Complex operator+(double x); //第一个参数是本类中的对象,可以使用成员函数
friend Complex operator+(double x,Complex y);//第1个参数不是本类中的对象
private:
double real;
double imag;
};
Complex Complex::operator+(double x)
{
Complex t;
t.real = real + x;
t.imag = imag;
return t;
}
Complex operator+(double x,Complex y)
{
Complex t;
t.real=y.real+x;
t.imag=y.imag;
return t;
}
int main()
{
Complex t;
Complex t1(1,2);
double d1=0;
d1=t1+3.5;
cout<<d1<<endl;
t=t1+d1;
t.display();
t=d1+t1;
t.display();
return 0;
}
重载复数与复数相加,复数与实数相加,复数与double数相加
最新推荐文章于 2024-07-15 13:32:43 发布