c++ - 关于 C++ 重载运算符

标签 c++ 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)

据我所知,前缀++ 的优先级高于二进制*。但在上面显示的输出中,前缀 ++ 被调用 after 二进制 *!是因为编译器将 operator+ 视为函数调用(这会导致未指定的行为)吗?我是否可以始终将重载运算符视为函数(当 xInt 时,这使得 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 when x is an Int)?

是也不是。如果 Int 与“普通”运算符做同样的事情,则否(直到 C++17),因为那将是未定义的行为。但是,如果 Int 没有改变 x++ 中的 x,那么是的。

关于c++ - 关于 C++ 重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45530216/

相关文章:

c++ - 访问 boost::geometry 多边形中的点数据时出错

c++ - 为什么++i 被认为是左值,而 i++ 不是?

c++ - 为什么我可以使用列表初始化普通数组而不使用赋值运算符

delphi - 如何将多个不同的记录(由于delphi限制而不是类)传递给一个函数?

javascript - 关于运算符优先级的困惑

c++ - 如何检索 QML 相机提要并发送到 C++ 后端

c++ - 从函数中获取两个数组并将它们存储在 C++ 中的不同数据类型数组中

java - 从 C++ 套接字读取 Java 中的数据

c++ - 无法识别 PRIxPtr

c++ - 提升 C++ 与 Python 的能力