您的位置:首页 > 其它

重载运算符的错误

2016-05-19 22:59 253 查看
1. 在用成员函数进行运算符重载时,只能有一个参数。否则出现错误:must take either zero or one argument;

2.错误:

#include<iostream>
using namespace std;

class Complex
{
public:
Complex(int r, int i){real=r; ima=i;}
int getR(){return real;}
int getI(){return ima;}
void display(){cout<<real<<" + "<<ima<<"i"<<endl<<endl;}
friend Complex operator + (Complex&, Complex&);
friend Complex operator - (Complex&, Complex&);

private:
int real;
int ima;
};
Complex Complex::operator + (Complex& a, Complex& b)<span style="white-space:pre">		</span>//error!
{
int r=a.getR()+b.getR();
int i=a.getI()+b.getI();
Complex c(r, i);
return c;
}
Complex Complex::operator - (Complex& a, Complex& b)<span style="white-space:pre">		</span>//error!
{
int r=a.getR()-b.getR();
int i=a.getI()-b.getI();
Complex c(r, i);
return c;
}

int main()
{
Complex a(3,5);	a.display();
Complex b(7,7); b.display();

Complex c=a+b;
cout<<"a+b=\n"; c.display();
Complex d=a-b;
cout<<"a-b=\n"; d.display();

return 0;
}
错误同1. 因加了Complex类的域名变成成员函数,而非友元函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: