作业帮 > 综合 > 作业

Complex operator +( Complex &, Complex &) 与Complex operator

来源:学生作业帮 编辑:搜狗做题网作业帮 分类:综合作业 时间:2024/05/27 10:55:22
Complex operator +( Complex &, Complex &) 与Complex operator +( Complex , Complex )区别和联系
#include
class Complex{
public:
Complex()
{
real=0;
imag=0;
}
Complex( double r)
{
real=r;
imag=0;
}
Complex(double r, double i):real(r),imag(i) {}
friend Complex operator + ( Complex & , Complex & );
void display();
private:
double real;
double imag;
};
Complex operator +( Complex &k, Complex &t) //这里用这个不对,但用Complex operator +( Complex //k, Complex t) 是对的.或者用Complex operator +( //const Complex &k, const Complex &t) 也是对的(下// 面///函数定义一起修改就行).说说这三种区别和联系
{
return Complex(k.real+t.real, k.imag+t.imag);
}
void Complex::display()
{
cout
Complex operator +( Complex &, Complex &) 与Complex operator
问题在于这句:
c3=c2+6.5;
6.5被自动转成临时对象,而临时对象是const类型的,可以参数这个文章 :
再问: 这只是解释了Complex operator +(const Complex & , const Complex &t)正确性。但是为什么

Complex operator +( Complex , Complex ) 这样声明的友元函数是对的??
再答: Complex operator +( Complex , Complex )这种声明也是正确的。

如果使用上面这种形式,那么c3=c2+6.5这句程序中,6.5首先转成一个临时对象,然后此对象被当作参数转递给友元函数,这时由于函数的参数的对象类型,不是引用类型,于是发生对象拷贝。