c++改错啦!!!!!!!

来源:百度知道 编辑:UC知道 时间:2024/07/02 01:26:53
class Complex
{
public:
double real, imag;
Complex();
};

Complex& operator+( Complex& a, Complex& b)
{
Complex *p = new Complex;
p->real = a.real + b.real;
p->imag = a.imag + b.imag;
return *p;
}
Answer:
It should return p ,not return *p.
Should we return a reference to object Complex? What solution do you provide?

class Complex
{
public:
double real, imag;
Complex();
};

Complex& operator+( Complex& a, Complex& b)
{
Complex *p = new Complex;
p->real = a.real + b.real;
p->imag = a.imag + b.imag;
return *p;
}
p是指针呀,你返回的是指针指向的值了,*p是在main函数中用塞

Of course you should return p because wut u should return is a reference Complex&:

Complex& operator+( Complex& a, Complex& b)

got it?