-5
我很困惑爲什麼兩個相同的表達式給出不同的結果?唯一的區別只在於表達式()我使用自定義基元包裝類型。爲什麼在處理對象或基本類型時C++的操作優先級不同++ a * b/b-- - a
我在代碼清晰度: struct Int { int value;
Int operator*(Int b) const{
return Int{value*b.value};
}
Int operator/(Int b) const{
return Int{value/b.value};
}
Int operator-(Int b) const{
return Int{value - b.value};
}
const Int& operator++() {
++value;
return *this;
}
Int operator--(int) {
Int copy{value};
value--;
return copy;
}
};
ostream& operator<<(ostream& out, Int x) {
out << x.value;
}
int main(){
int a = 11; Int A{11};
int b = 4; Int B{4};
cout << ++a/b * b-- - a << endl; // 0
cout << ++A/B * B-- - A << endl; // 4
}
此外,Clang編譯器顯示警告-Wunsequenced,但只適用於具有原始類型的表達式。
假設它在C++中是未定義的行爲 – MrTux
好吧,但是爲什麼我們只能用原始類型獲得警告?這是否意味着使用類來定義操作順序? –
兩者都未定義,但是clang只能檢測基元類型的無序修改 - 它不會「知道」您的操作符修改了這些對象。 – molbdnilo