代码之家  ›  专栏  ›  技术社区  ›  Irtiaz Kabir

当对一个对象进行多次操作时,如何禁止增量运算符?

  •  -1
  • Irtiaz Kabir  · 技术社区  · 3 年前

    如何重载递增运算符,使此代码无效-

    Point p(2, 3);
    ++++p;
    

    同时允许以下内容-

    Point p(2, 3), a(0, 0), b(1, 4);
    a = ++p + b;
    

    就像在C中一样,这是无效的-

    int a = 2;
    ++++a;
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Adrian Mole Chris    3 年前

    单向你 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;
    }
    
    推荐文章