msdn里有一个例子。 重载operator相当于出现某个操作符的时候应该调用你的类(或结构)的某个成员函数或友元函数。 下例重载了类Complex的+号Complex a(2,3); Complex b(3,4); a + b 相当于执行了a.operator+(b)(member function 1) 5 + a 相当于执行了operator+(5, b)(friend function 2)//因为5不是Complex类,所以它没法调用成员函数,只能用一个全局函数来代替。但这个函数必须声明位Complex的友元函数。BTW, 友元函数在重载操作符时非常有用,它可以使非类的一个函数访问类私有变量。// Example of the operator keyword class Complex { public: Complex( float re, float im ); Complex operator+( Complex &other );//1 friend Complex operator+( int first, Complex &second );//2 private: float real, imag; };// Operator overloaded using a member function Complex Complex::operator+( Complex &other ) { return Complex( real + other.real, imag + other.imag ); };// Operator overloaded using a friend function Complex operator+( int first, Complex &second ) { return Complex( first + second.real, second.imag ); }
重载operator相当于出现某个操作符的时候应该调用你的类(或结构)的某个成员函数或友元函数。
下例重载了类Complex的+号Complex a(2,3);
Complex b(3,4); a + b 相当于执行了a.operator+(b)(member function 1)
5 + a 相当于执行了operator+(5, b)(friend function 2)//因为5不是Complex类,所以它没法调用成员函数,只能用一个全局函数来代替。但这个函数必须声明位Complex的友元函数。BTW, 友元函数在重载操作符时非常有用,它可以使非类的一个函数访问类私有变量。// Example of the operator keyword
class Complex
{
public:
Complex( float re, float im );
Complex operator+( Complex &other );//1
friend Complex operator+( int first, Complex &second );//2
private:
float real, imag;
};// Operator overloaded using a member function
Complex Complex::operator+( Complex &other )
{
return Complex( real + other.real, imag + other.imag );
};// Operator overloaded using a friend function
Complex operator+( int first, Complex &second )
{
return Complex( first + second.real, second.imag );
}