Amj*_*tib 6 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();
}
Run Code Online (Sandbox Code Playgroud)
它给出了以下错误:
Error C2676: binary '++': 'Unary' does not define this operator or a conversion to a type acceptable to the predefined operator
Run Code Online (Sandbox Code Playgroud)
运算符++实际上有两种含义,取决于它是用作前缀还是用作后缀运算符。当以一种方式或另一种方式使用时,C++ 期望在您的类中定义哪个函数的约定如下:
class Unary {
public:
Unary& operator++ (); // prefix ++: no parameter, returns a reference
Unary operator++ (int); // postfix ++: dummy parameter, returns a value
};
Run Code Online (Sandbox Code Playgroud)
您的函数void operator++()不符合此约定,这就是出现错误的原因。
实现可能如下所示:
Unary Unary::operator++(int)
{
x++;
y++;
return *this;
}
Run Code Online (Sandbox Code Playgroud)