单向你
operator++()
返回a
const
参考这将阻止后续修改返回值,如在“链式”中
++++p;
这是一个大纲版本,其中还包括所需的二进制加法运算符,作为非成员函数实现(
as is normal
):
#include <iostream>
class Point {
public:
int x{ 0 }, y{ 0 };
Point(int a, int b) : x{ a }, y{ b } {}
const Point& operator++() { ++x; ++y; return *this; }
Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; }
};
inline Point operator+(Point lhs, const Point& rhs)
{
lhs += rhs;
return lhs;
}
int main()
{
Point p(2, 3), a(0, 0), b(1, 4);
a = ++p + b; // OK: The result of the ++p is passed by value (i.e. a copy)
std::cout << a.x << " " << a.y << "\n";
// ++++a; // error C2678: binary '++': no operator found which takes a left-hand operand of type 'const Point'
return 0;
}