(1)输入、输出重载必须定义非成员函数,并在类创建时声明为友元;
(2)=、[]、->必须定义为成员,否则编译器会出错;
(3)对称Operator,算术操作符(+/-/*//),关系操作符(== ,> , < , !),最好定义为普通非成员函数;
(4)如果定义为成员函数,则参数少一个,否则该多少就多少。之所以少一个,是因为第一个参数被默认为this的指向;
(5)改变对象状态或与类型关系密切的,最好定义为类成员。例如:++ ,-- ,*(解引用)。
简单的示例代码:
<span style="font-size:14px;">#include <iostream>
using namespace std;
class Four{
friend Four operator+(const Four & l,const Four & r);
friend ostream& operator<<(ostream& out,const Four &f);
friend istream& operator>>(istream& in, Four &f);
public:
Four():a(0),b(0),c(0),d(0){}//默认构造函数是必要的,初始化列表是必要的,因为const,引用参数,以及没有默认构造函数的类参数的存在
Four(int a,int b,int c,int d){
this->a = a;
this->b = b;
this->c = c;
this->d = d;
}
/*Four operator+(const Four &r){
//Four ret;
this->a += r.a;
this->b += r.b;
this->c += r.c;
this->d += r.d;
return *this;
}*/
void print(){
cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
}
private:
int a;int b; int c; int d;
};
Four operator+(const Four& l,const Four& r){
Four ret(l);
ret.a += r.a;
ret.b += r.b;
ret.c += r.c;
ret.d += r.d;
return ret;
}
ostream& operator <<(ostream & out, const Four & f){
out<<f.a<<" "<<f.b<<" "<<f.c<<" "<<f.d;
return out;
}
istream& operator>>(istream& in, Four &f){
in>>f.a>>f.b>>f.c>>f.d;
//in>>f.b;
//in>>f.c;
//in>>f.d;
return in;
}
int main() {
// your code goes here
Four l(1,2,3,4);
Four r(4,3,2,1);
Four sum;
sum = l + r;
cout<<sum<<endl;
Four f;
cin>>f;
cout<<f<<endl;
return 0;
}</span>