-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