#include<iostream> using namespace std; class Complexs{ public: Complexs(double r=0,double i=0):real(r),imag(i){ } void print()const; // 按指定格式输出结果 //**********found********** Complexs operator+(Complexs & c); // 加法运算 //**********found********** friend Complexs& operator*(Complexs c1,Complexs c2); // 乘法运算 private: double real,imag; // 复数的实部和虚部 }; void Complexs::print()const { cout<<real; if(imag<0)cout<<imag<<'i'<<endl; else if(imag>0) cout<<'+'<<imag<<'i'<<endl ; } Complexs Complexs::operator+(Complexs & c) { Complexs t; t.real=real+c.real; t.imag=imag+c.imag; //**********found********** return t; } //**********found********** Complexs operator*(Complexs c1,Complexs c2) { Complexs c; c.real=c1.real*c2.real-c1.imag*c2.imag; //**********found********** c.imag=c1.real*c2.imag+c1.imag*c2.real; return c; } int main() { Complexs z1(2.0,3.0),z2(1.0,-4.0),z; cout<<"z1:"; z1.print(); cout<<"z2:"; z2.print(); z=z1+z2; cout<<"z1+z2:"; z.print(); z=z1*z2; cout<<"z1*z2:"; z.print(); system("pause"); return 0; }错在哪
时间: 2023-07-06 21:42:18 浏览: 66
#include_iostream.h_
4星 · 用户满意度95%
代码中的 `friend Complexs& operator*(Complexs c1,Complexs c2)` 函数返回了一个 Complexs 的引用,但实际上返回的是一个临时对象的地址,这样的写法是错误的。
应该将其改为返回一个 Complexs 对象,即 `friend Complexs operator*(Complexs c1, Complexs c2)`。
修改后的代码如下:
阅读全文