[英]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;
}
從上面的代碼中,我重載了后綴增量和后綴一元減號。 我知道后綴一元減號沒有意義,但我想知道為什么我對x-有編譯錯誤並且x--和x.operator-(0)操作沒有任何問題。
我在 DevC++ 中編譯了這段代碼,我得到了以下錯誤。
[Error] expected primary-expression before ';' token
x-有什么問題?
x-
有什么問題?
沒有錯; 這是由語言設計的。 你會看到同樣的錯誤
1 - ;
意思是, operator -
期望一個參數可以像你在下一行中所做的那樣工作
x.operator-(0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.