关于 C++ 重载运算符
About the C++ overloaded operators
运行我电脑上的以下程序
#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)
据我所知,前缀 ++
的优先级高于二进制 *
。但在上面显示的输出中,前缀 ++
在 二进制 *
之后被调用 !是因为编译器将 operator+ 视为函数调用(这会导致未指定的行为)吗?我是否可以始终将重载运算符视为函数(当 x
是 Int
时,这使得 x = x++
的行为定义明确)?
谢谢!
As far as I known, the prefix ++
has higher precedence than binary *
.
优先级高并不是说前缀自增会在乘法运算符之前被调用,而是参数以何种顺序绑定到相应的运算符上。
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 when x
is an Int
)?
是也不是。如果 Int
与 "normal" 运算符做同样的事情,则否(直到 C++17),因为那将是未定义的行为。但是,如果 Int
没有改变 x++
中的 x
,那么是的。
运行我电脑上的以下程序
#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)
据我所知,前缀 ++
的优先级高于二进制 *
。但在上面显示的输出中,前缀 ++
在 二进制 *
之后被调用 !是因为编译器将 operator+ 视为函数调用(这会导致未指定的行为)吗?我是否可以始终将重载运算符视为函数(当 x
是 Int
时,这使得 x = x++
的行为定义明确)?
谢谢!
As far as I known, the prefix
++
has higher precedence than binary*
.
优先级高并不是说前缀自增会在乘法运算符之前被调用,而是参数以何种顺序绑定到相应的运算符上。
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
与 "normal" 运算符做同样的事情,则否(直到 C++17),因为那将是未定义的行为。但是,如果 Int
没有改变 x++
中的 x
,那么是的。