c++ 重载运算符实现复数相加

来源:百度知道 编辑:UC知道 时间:2024/06/04 01:12:18
class complex
{
public:
double real,image;
complex(double r=0,double i=0)//带缺省参数构造函数
{ real=r; image=i;}
};

main()
{
complex operator+(complex com1,complex com2)
{
complex temp;
temp.real=com1.real+com2.real;
temp.imag=com1.imag+com2.imag;
return temp;
}
return 0;
}

哭啊。。。怎么还是不对啊

另外 那种temp.real com1.real 这种样子的什么意思啊为什么中间有个点阿?是访问???还是什么 急啊~~~50分在线等!

1、怎么还是不对啊 =>
重载类运算符要这样:

class complex
{
public:
....

complex &operator + (const complex &a)
{
this->real+=a.real;
this->imag+=a.imag;
return *this;
}
}; // end of class complex

应用:
int main()
{
complex m(1,1),n(2,2),p(0,0);
p=m+n;
return 0;
}

2、那种temp.real com1.real 这种样子的什么意思啊 =>
temp和com1是complex类的实例,temp.real com1.real是对类complex公有成员变量的引用。

temp.real:类成员变量
你的重载运算符函数有问题。
class complex
{
public:
double real,image;
complex(double r=0,double i=0)
{ real=r; image=i;}
//重载运算符函数
complex complex::operator+( const complex &operand2 ) const
{
return complex( real + operand2.real,image + operand2.image);
}
};
//例子
int main()
{
complex a(1,2),b(2,3);
complex d;
d=a+b;
cout<<d.real<<"+"<<d