c++ - 如何正确重载后缀增量运算符?

标签 c++ operator-overloading compiler-warnings postfix-operator

有没有办法修改这段代码,这样我在编译时就不会收到警告?此外,这段代码是否会导致段错误,因为它要访问以检索 main 中 x 的值的内存在运算符函数调用结束时被释放了?

class A {

  int x; /* value to be post-incremented */

  public:

  A() {  /* default constructor */
  }

  A( A & toCopy ) {   /* copy constructor */
    x = toCopy.x;
  }

  A & operator++(int) {  /* returns a reference to A */

    A copy( *this );         /* allocate a copy on the stack */
    ++x;

    return copy;            /* PROBLEM: returning copy results in a warning */

  }                         /* memory for copy gets deallocated */

}; /* end of class A */

int main() {

  A object;
  object.x = 5;

  cout << (object++).x << endl;   /* Possible segfault ? */

}

最佳答案

您需要返回一个值(不是引用):

A operator++(int) { /*...*/ }

这将解决编译器警告,您不会以悬空引用结束。

关于c++ - 如何正确重载后缀增量运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18748757/

相关文章:

c++ - Python 嵌入 C++

c++ - 为什么 Visual C++ 接口(interface)不能包含运算符?

C++ 重载 : overload of operator =

c++ - 避免警告 'Unreferenced Formal Parameter'

C++:为用户定义的类型进行转换

c++ - 如何在 Eclipse 中调试 Android 上 OpenCV 示例的 native 代码?

c++ - 在 block 作用域中使用 extern

c++ - 从结构 vector 中,获取一个 vector ,该 vector 收集每个结构的字段之一

C++,通过指针传递泛型数组,继承,错误: no operator which takes a right-hand operand

c++ - boost::system::(...)_category 已定义但未使用