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类的域名变成成员函数,而非友元函数