gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:04:36 26 4
gpt4 key购买 nike

有没有办法修改这段代码,这样我在编译时就不会收到警告?此外,这段代码是否会导致段错误,因为它要访问以检索 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com