c++ - 运算符重载小技巧
重载 () :
多次调用(),然后再调用print()
class A{
public:
A operator()(int a)
{
cout << a <<endl;
return *this;
}
void print()
{
cout << "hello"<<endl;
}
};
int main()
{
A a;
a(54)(434).print();
//54
//434
//hello
}
重载 ++ :
++ 运算符,还可分为前缀 ++ 和后缀 ++ 运算符。
class Length
{
private:
int len_inches;
public:
//前缀++的声明
Length operator++ ();
//后缀++的声明
Length operator++ (int);
};
重载前缀++运算符:
C++允许重载前缀运算符,以使表达式 ++b 能递增 b 的长度值,并返回结果对象。该运算符可以作为成员函数来重载,这使得它的单个形参是隐含的, 所以重载运算符不需要形参。
Length Length::operator++ ()
{
len_inches ++;
return *this;
}
重载后缀++运算符:
后缀递增运算符 b++ 也可以递增b的长度,但与前缀版本不同,因为它返回对象在增加之前的值。重载后缀递增运算符与重载前缀版本稍有不同。
以下是为 Length 类重载后缀递增运算符的函数:
Length Length::operator++(int)
{
Length temp = *this;
len_inches ++;
return temp;
}
重载«:
class Complex
{
double real,imag;
public:
Complex( double r=0, double i=0):real(r),imag(i){ };
friend ostream & operator<<( ostream & os,const Complex & c);
};
ostream & operator<<( ostream & os,const Complex & c)
{
os << c.real << "+" << c.imag << "i"; //以"a+bi"的形式输出
return os;
}