问一个关于运算符重载里面参数的问题。
friend Complex operator + (Complex c1,Complex c2);事先定义了转换构造函数,但是接下来在这个友员函数定义里面,参数不能用引用Complex &c1,Complex &c2),用引用的话则会出现以下错误
binary '+' : no operator defined which takes a left-hand operand of type 'double' (or there is no acceptable conversion)
这个我想c4=i+c1; 这时i不是复数类型,调用转换构造函数,但是引用应该没关系的啊?原因实部是只能用值传递才能使得转换构造函数初始化?
我发现也可以把Complex(double r){real=r;imag=0;}修改成Complex(double &r){real=r;imag=0;}加一个引用符号,尽量减少时空开销。
我觉得尽管用了转换构造函数,可以使得运算符重载后不许重载更多就能适应交换律,但是这样,反而增加了时空开销,虽然不那么麻烦了。
#include <iostream.h>
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex(double r){real=r;imag=0;}
friend Complex operator + (Complex c1,Complex c2);
friend Complex operator - (Complex c1,Complex c2);
friend Complex operator * (Complex c1,Complex c2);
friend Complex operator / (Complex c1,Complex c2);
void display();
private:
double real;
double imag;
};
Complex operator + (Complex c1,Complex c2)
{return Complex(c1.real+c2.real,c1.imag+c2.imag);}
Complex operator - (Complex c1,Complex c2)
{return Complex(c1.real-c2.real,c1.imag-c2.imag);}
Complex operator * (Complex c1,Complex c2)
{return Complex(c1.real*c2.real-c1.imag*c2.imag,c1.imag*c2.real+c1.real*c2.imag);}
Complex operator / (Complex c1,Complex c2)
{return Complex((c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),
(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));}
void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}
int main()
{
Complex c1(3,4),c2(5,-10),c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14;
double i=5;
c3=c1+c2;
cout<<"c1=";c1.display();cout<<"c2=";c2.display();
cout<<"c1+c2=";c3.display();
c4=i+c1;
cout<<"i="<<i;cout<<",c1=";c1.display();
cout<<"i+c1=";c4.display();
c5=c2+i;
cout<<"i="<<i;cout<<",c2=";c2.display();
cout<<"c2+i=";c5.display();
c6=c1-c2;
cout<<"c1=";c1.display();cout<<"c2=";c2.display();
cout<<"c6=c1-c2=";c6.display();
c7=c1-i;
cout<<"i="<<i;cout<<",c1=";c1.display();
cout<<"c7=c1-i=";c7.display();
c8=i-c2;
cout<<"i="<<i;cout<<"c2=";c2.display();
cout<<"c8=i-c2=";c8.display();
c9=c1*c2;
cout<<"c1=";c1.display();cout<<"c2=";c2.display();
cout<<"c9=c1*c2=";c9.display();
c10=c1*i;
cout<<"i="<<i;cout<<",c1=";c1.display();
cout<<"c10=c1*i=";c10.display();
c11=i*c2;
cout<<"i="<<i;cout<<",c2=";c2.display();
cout<<"c11=i*c2=";c11.display();
c12=c1/c2;
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c12=c1/c2=";c12.display();
c13=c1/i;
cout<<"i="<<i;cout<<",c1=";c1.display();
cout<<"c13=c1/i=";c13.display();
return 0;
}