c++ - c2676 - 二进制 '++' 未定义此运算符

标签 c++ oop visual-studio-2015

我无法编译下面的代码,但我可以用另一台笔记本电脑在 visual studio 下编译它,如果有不同的配置需要设置,我不会拒绝。

#include<iostream>
using namespace std;
class Unary {
private:
    int x, y;

public:
    Unary(int i = 0, int j = 0) {
        x = i;
        y = j;
    }
    void show()
    {
        cout << x << " " << y << endl;
    }
    void operator++()
    {
        x++;
        y++;
    }
};

int main() {
    Unary v(10, 20);
    v++;
    v.show();
}

它给出了以下错误:

Error C2676: binary '++': 'Unary' does not define this operator or a conversion to a type acceptable to the predefined operator

最佳答案

Operator ++ 实际上有两种含义,取决于它是用作前缀运算符还是用作后缀运算符。当以一种方式或另一种方式使用时,C++ 希望在您的类中定义哪个函数的约定如下:

class Unary {
  public:
    Unary& operator++ ();    // prefix ++: no parameter, returns a reference
    Unary operator++ (int);  // postfix ++: dummy parameter, returns a value
};

你的函数void operator++()不满足这个约定,所以才会出现这个错误。

实现可能如下所示:

Unary Unary::operator++(int)
{
    x++;
    y++;
    return *this;
}

关于c++ - c2676 - 二进制 '++' 未定义此运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49711535/

相关文章:

java - 服务层设计,在哪里检查权限,如何处理UI层

php - 验证域对象 setter 中的表单输入?

visual-studio-2015 - 为什么有些项目模板在 Visual Studio Community 2015 中丢失,但出现在新项目模板搜索中?

c++ - 如何在 OpenGL C++ 中旋转旋转轴?

c++ - 如何在 C++ 中实现无操作宏(或模板)?

c++ - WM_COPYDATA 无法正确传送我的字符串

c++ - 在同一个应用程序中使用 Legacy OpenGL 和 Modern OpenGL

java - 从工厂中的字符串参数获取正确的对象

visual-studio-2015 - 从命令行 VS15/W10 生成 UWP .appxupload

c++ - 未调用重载的赋值运算符