(转)初识operator重载操作符

#include<iostream>
using namespace std;
class myclass{
     int i;
public:
     myclass(int k = 0):i(k){};      //bool operator==(const myclass&);
     friend bool operator==(const myclass& a,const myclass& b);
}; //bool myclass::operator==(const myclass& a){
//     if(this->i==a.i)
//          return 1;
//     else
//          return 0;
//}

bool operator==(const myclass& a,const myclass& b){
     if(a.i==b.i)
          return 1;
     else
          return 0;
}
int main(){
     myclass a(1),b(2);
     cout<<(a==b)<<endl;
}
在用类成员方式重载重载操作符时,我写成了这个形式bool myclass::operator==( const myclass& a,const myclass& b)报错说:must take exactly one argument,原因如下:
用成员方式重载运算符,   不能改变参数的个数  ,二元运算符用成员重载时,   只需要一个参数,   另一个参数由this指针传入  。如果需要两个参数,那么可以在类外面定义,然后在类里声明为友元。
posted @ 2015-07-22 14:59  川子61  阅读(277)  评论(0编辑  收藏  举报