[英]Does C++ compiler treat all postfix operator overloading as same (postfix version of - and --)?
#include <cstdio>
#include <iostream>
using namespace std;
class Int32 {
int num;
public:
Int32(int num = 0) : num(num) {}
~Int32() {}
int value() { return num; }
Int32 & operator - (int x) { cout << "Postfix of -" << endl; return *this; }
Int32 & operator -- (int x) { cout << "Postfix of --" << endl; return *this; }
};
int main() {
Int32 x(100);
x--;
x-; // [Error] expected primary-expression before ';' token
x.operator-(0);
return 0;
}
From the above code I overloaded postfix increment and postfix unary minus .从上面的代码中,我重载了后缀增量和后缀一元减号。 I know postfix unary minus doesn't make sense, but I wonder why I have compilation error for x- and don't have any issue with x-- and x.operator-(0) operations.
我知道后缀一元减号没有意义,但我想知道为什么我对x-有编译错误并且x--和x.operator-(0)操作没有任何问题。
I compiled this code in DevC++ and I got following error.我在 DevC++ 中编译了这段代码,我得到了以下错误。
[Error] expected primary-expression before ';' token
What is wrong with x- ? x-有什么问题?
What is wrong with
x-
?x-
有什么问题?
Nothing wrong with it;没有错; This by language design.
这是由语言设计的。 You will see the same error with
你会看到同样的错误
1 - ;
meaning, the operator -
expect an argument to work with like you did it in the next line意思是,
operator -
期望一个参数可以像你在下一行中所做的那样工作
x.operator-(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.