C++:运算符重载:类内和类外。预自增运算符的歧义

标签 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;
}

在每种情况下,都会选择运算符的类内重载来反对同一运算符的任何其他类外重载,但预自增运算符是不同的:它会导致类内和类外重载之间的歧义.

为什么?

最佳答案

您的后自增成员运算符不是 const 成员,而非成员 const A& 参数。没有歧义,并且选择了非常量版本。这同样不适用于预增量版本。成员和非成员都绑定(bind)到非常量 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)

关于C++:运算符重载:类内和类外。预自增运算符的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30087527/

相关文章:

c - 为什么交换变量名会改变 C 程序的输出?

c++ - 无法访问 std::move(...) C++ 11

c++ - 运算符->有什么特别之处以及它是如何工作的?

c++ - 在一个命令中使用 2 个重载运算符会导致错误

lambda - 使用 lambda 表达式的后缀与前缀递增

c - 前后增量运算符分析结果

c++ - C++11 中operator=(std::promise &&) 的结果是什么?

c++ - 使用鼠标回调修改类中的 Mat 属性

c++ - 为什么这段代码可以编译?

c# - "ulong == ulong?"评估为 "ulong == ulong"工作正常