我无法编译下面的代码,但我可以用另一台笔记本电脑在 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/