/**
C++操作符重载时,首先找成员函数是否已经有相关实现,如果有相关的实现,则优先调用成员函数的操作符重载,如果没有的话,则调用全局的操作符重载.
总结:
1) 不可以重载的操作符 (1) :: (2) .* (3) ?:
2) 重载操作符必须有一个类类型或枚举类型,意思是不能重载内置的基本数据类型的操作符
3) 优先级和结合性是固定的
4) 不保证操作符的调用顺序
5) 类成员函数和非类成员函数: 比较操作符适用于非类成员,赋值操作适用于类成员.如果对于同一个操作,既定义了member function,也定义非member function,则member operator overwrite function优先级高
6) 对于none member function的操作符重载,往往需要声明为friend,以便访问private data.
7) 可以使用操作符重载显示调用
如 item1 + item2; //优先调用member function,若无实现,则调用none member function
等价于 operator + ( iterm1,item2)
author : openxmpp@163.com
date 2013-2-23
*/
#include <iostream>
using namespace std;
#include <string>
using std::string;
class MyClass
{
friend bool operator < ( const MyClass &value1, const MyClass &value2 );
friend bool operator == ( const MyClass &value1, const MyClass &value2 );
public:
explicit MyClass( int value )
{
mNumber = value;
}
bool operator < ( const MyClass & value )
{
cout << "member function operator < called " << mNumber << " " << value.mNumber<<endl;
return this->mNumber < value.mNumber;
}
bool operator == ( const MyClass & value )
{
cout << "member function operator == called " << mNumber << "\t" << value.mNumber<<endl;
return this->mNumber == value.mNumber;
}
MyClass & operator + ( const MyClass & rvalue )
{
cout << "member function operator + called "<< mNumber << "\t" << rvalue.mNumber<<endl;
mNumber += rvalue.mNumber;
return *this;
}
private:
int mNumber;
};
bool operator < ( const MyClass &lValue, const MyClass &rValue )
{
cout << "operator global operator < called"<<endl;
return lValue.mNumber == rValue.mNumber;
}
bool operator == ( const MyClass &lValue,const MyClass &rValue )
{
cout << "operator global operator == called"<<endl;
return lValue.mNumber == rValue.mNumber;
}
//这将导致编译错误,不能重载内置的基本数据类型的操作符
#if 0
bool operator == ( int lValue,int rValue)
{
return lValue < rValue;
}
#endif
int main(int argc, char *argv[])
{
MyClass c(1024);
MyClass d(2048);
c + d; //调用MyClass的 operator + ,这里期望是返回的一个临时变量,但结果是在原地修改c的值了,违背设计初衷,因此,对于累加的操作符,建议定义为全局的
operator == ( c,d ); //bool operator == ( const MyClass &lValue,const MyClass &rValue )
d == c + c; //优先级和结合性是固定的,先是"+",再是"=="
return 0;
}