关于C++的复数运算问题!!!

来源:百度知道 编辑:UC知道 时间:2024/06/18 01:43:12
请帮找出程序的错误之处,并指出为什么不能那样
#include<iostream>
using namespace std;
class complex
{public:
complex(){real=0;imag=0;}
complex(double r,double i)
{real=r;
imag=i;
}
complex operator+(complex &c1,complex &c2)
{complex c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
void display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}
private:
double real;
double imag;
};
int main()
{complex c1(2,1),c2(3,4),c3;
c3=c1+c2;
c3.display();
return 0;
}
编译出错提示:
error C2804: binary 'operator +' has too many parameters
error C2333: '+' : error in function declaration; skipping function body
error C2676: binary '+' : 'class complex' does not define this operator or a conversion to a type acceptable to the predefined o

错误改了,好了,原因就写在程序注释里,自己看看
#include<iostream>
using namespace std;
class complex
{public:
complex(){real=0;imag=0;}
complex(double r,double i)
{real=r;
imag=i;
}
complex operator+(complex &c2) //因为你重载运算符+是类的成员函数,第一个形参默认是一个this指针,

//如果你自己写了两个形参,那岂不是不对应,出现错误,如果你重载运算符+函数
{complex c; //是类的友元函数,则形参需写两个,因为这时候没有了默认的this指针,这两种方法自己选择吧
c.real=this->real+c2.real; //为了让你看清楚,我把this指针写了出来,可以不写的
c.imag=this->imag+c2.imag;
return c;
}

void display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}
private:
double real;
double imag;
};

int main()
{complex c1(2,1),c2(3,4),c3;
c3=c1+c2;
c3.display();
return 0;
}

complex operator+(complex &c1,complex &c2) 要定义为友元;
你再改改吧!

你没有声名complex operator+(comple