c++ - 重载后增量

标签 c++

假设我们有一个类 myClass 存储一个 int。我想重载标准运算符,例如 +=+=++ 等。我怎样才能重载后缀增量,即operator++(int),以便在计算表达式之后完成实际增量?我的意思是,在执行以下代码之后,

myClass object1(0), object2(1);
object1 = object2++ + object2;

我希望 object1 和 object2 都保留 2。

天真的方法

myClass& operator++(int){
  myClass tmp(x) //x - stored value
  ++x;
  return tmp;
}

不起作用,因为 +++ 之前调用。

我一直在寻找这个问题的答案,但没有找到任何相关的内容。坦率地说,直到最近我还认为不可能做到这一点。

最佳答案

您的代码:

myClass object1(0), object2(1);
object1 = object2++ + object2;

根据 §8.3.6/9,实际上具有未指定的行为:

The order of evaluation of function arguments is unspecified.

并且由于该表达式被转换为如下内容:

operator=(objec1, operator+(operator++(.., object2), object))

避免这种不便的明显方法是在求和之后执行增量:

object1 = object + object2;
object++;

或(假设还定义了operator*):

object1 = object2 * 2;
object++;

根据 §1.9/15,如果它们是标量类型,这将是未定义的行为:

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. — end note ] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, and they are not potentially concurrent (1.10), the behavior is undefined.

关于c++ - 重载后增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30539849/

相关文章:

c++ - <algorithm> 是否包含 <cmath>?

c++ - 在 C++ 中插入线程二叉树

c++ - typedef decltype 函数指针未返回正确的输出(cout)

c++ - 在什么意义上 const 只允许对可变成员变量进行原子更改?

c++ - 未定义对 `main' 的引用 - 但包含主要功能

python - 如何从 C++ 启动 Python 线程?

C++、比较器和模板

c++ - Eclipse C++ 构建错误 : no such file or directory

c++ - setShortcut 的多个键盘快捷键

c++ - 使用 TMP 计算表示值所需的位数