C++ 类能够重载各个运算符,比较特殊的 前缀和后缀运算符应该如何区分呢?
结论:重载后缀时,需要传递一个int 参数来和前缀区分,具体代码示例如下。
代码以前缀++和后缀++来示例。
class Point
{
public:
Point(int x, int y):m_x(x),m_y(y)
{
}
// 其他函数不是讨论重点,故省略...
Point & operator++() // 前缀++ 运算符
{
++m_x;
++m_y;
cout<<"++前缀"<<endl;
return *this;
}
Point & operator++(int) // 后缀++ 运算符
{
Point temp = *this;
++m_x;
++m_y;
cout<<"后缀++"<<endl;
return temp;
}
private:
int m_x;
int m_y;
};