C ++中的函数可以返回某些内容然后执行其代码吗?

时间:2020-06-30 13:04:39

标签: c++ operators

当做这样的事情时:

i2 = i++;

++运算符将返回i,然后将i加1。

函数还能返回某些内容然后执行其代码吗?

2 个答案:

答案 0 :(得分:2)

否,一旦函数的作用域结束(在结束}时),就无法再执行任何代码。

但是,该函数可以存储输入的旧状态,修改输入并返回输入的旧值。该函数返回值后,给出执行代码后的效果。例如:

int f(int &n) {
  int x = n;    // store input
  n = 42;       // input is modified before return
  return x;     // old input is returned
}

int b = f(a);  // b is equal to a
               // but now a is 42

如您所见,后递增是此类行为有用的一个示例。另一个示例是std::exchange,它的外观是在返回值之后修改输入

答案 1 :(得分:0)

如果您要自己实现后缀增量,则应先存储原始值,然后使用增量,但仍返回原始值:

Number Number::operator++ (int)
{
  Number ans = *this;
  ++(*this);
  return ans;
}

您可以查看此常见问题解答以了解更多详细信息:https://isocpp.org/wiki/faq/operator-overloading#increment-pre-post-overloading

因此,在C++中返回后就不会执行任何功能代码。