c2676-二进制'++'未定义此运算符 [英] c2676 - binary '++' does not define this operator

查看:141
本文介绍了c2676-二进制'++'未定义此运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法编译以下代码,但是我可以在Visual Studio下使用另一台笔记本电脑对其进行编译,如果设置不同,我也不是没有.

I'm not able to compile the below code, but i'm able to compile it under visual studio with another laptop, I don't no if there are a different configuration that shout be set.

#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

推荐答案

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

Operator ++ actually has two meanings, depending on whether it is used as prefix or as postfix operator. The convention of which function C++ expects to be defined in your class when used in the one way or in the other is as follows:

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

您的函数void operator++()不满足此约定,这就是错误出现的原因.

Your function void operator++() does not fulfil this convention, that's why the error appears.

实现可能如下所示:

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

这篇关于c2676-二进制'++'未定义此运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆