C ++:运算符重载:类内和类外。与preincrement运算符的歧义

时间:2015-05-06 21:07:31

标签: c++ operator-overloading pre-increment

查看this code

struct A
{
    A operator+(A const& a) { cout << 1 << endl; return A(); }
    A& operator++() { cout << 2 << endl; return *this; }
    A operator++(int) { cout << 3 << endl; return *this; }
    bool operator!() { cout << 4 << endl; return true; }

};

A operator+(A const& a, A const& b)
{ cout << 5 << endl; return A(); }

A& operator++(A& a) { cout << 6 << endl; return a; }
A operator++(A const& a, int) { cout << 7 << endl; return A(); }
bool operator!(A const& a) { cout << 8 << endl; return false; }

int main()
{
    A a, b;

    a + b; // Prints 1 instead 5
    ++a;   // Ambiguity
    a++;   // Prints 3 instead 7
    !a;    // Prints 4 instead 8

    return 0;
}

在每种情况下,操作符的类内重载都选择同一运算符的任何其他类外重载,但是preincrement运算符是不同的:它导致类内和类外重载之间的歧义

为什么?

1 个答案:

答案 0 :(得分:4)

您的增量后成员运算符不是const成员,而非成员一个const A&参数。没有歧义,选择了非const版本。这同样适用于预增量版本。成员和非成员都绑定到非const A,因此含糊不清。

查找

// non-const member. Does not require A operand to be const
A operator++(int)

// non-member. Requires A operand to be const
A operator++(A const& a, int)