在我的电脑上运行下面的程序
#include <iostream>
class Int {
public:
Int(int x) : val{x} {}
Int operator++() {
std::cout << "Int::operator++()\n";
return ++val;
}
friend Int operator+(Int a, Int b) {
std::cout << "operator+(Int, Int)\n";
return a.val + b.val;
}
friend Int operator*(Int a, Int b) {
std::cout << "operator*(Int, Int)\n";
return a.val * b.val;
}
private:
int val;
};
int main()
{
Int a = 1, b = 2;
b = ++a + b * b;
return 0;
}
我得到了这个输出:
operator*(Int, Int)
Int::operator++()
operator+(Int, Int)
据我所知,前缀++
的优先级高于二进制*
。但在上面显示的输出中,前缀 ++
被调用 after 二进制 *
!是因为编译器将 operator+ 视为函数调用(这会导致未指定的行为)吗?我是否可以始终将重载运算符视为函数(当 x
是 Int
时,这使得 x = x++
的行为定义明确)?
谢谢!
最佳答案
Is it because the compiler treats the
operator+
as a function call (which leads to Unspecified Behavior)?
是的。但请注意,++a
是否在 b * b
之后求值并不重要,因为最终这两个值会正确相加,这符合运算符优先级规则。
没有赋值的表达式等同于:
operator+(a.operator++(), operator*(b, b))
函数参数的求值顺序是未指定的,因此从技术上讲,++a
可以在 b * b
之前求值,但也可以反过来。
Can I always consider an overloaded operator as a function (which makes the behavior of
x = x++
well-defined whenx
is anInt
)?
是也不是。如果 Int
与“普通”运算符做同样的事情,则否(直到 C++17),因为那将是未定义的行为。但是,如果 Int
没有改变 x++
中的 x
,那么是的。
关于c++ - 关于 C++ 重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45530216/