gpt4 book ai didi

c++ - 析构函数之前工作。如何?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:14 25 4
gpt4 key购买 nike

#include<iostream>

using namespace std;
class test
{
int a;
public:
test()
{
a=0;
}
test operator ++(int)
{ a++;
return *this;
}
void display()
{
cout<<a;
}
~test() {
cout << "DES" << endl;
}
};
int main()
{
test t,t1;
t1 = t++;
t.display();
system("pause");
}

我得到的输出是:

DES
1Press any key to continue...
DES
DES

为什么析构函数之前起作用?

最佳答案

表达式 t++ 产生一个 test 类型的临时对象,因为 operator++(int) 按值 [*] 返回。在 operator= 完成使用它分配 t1 的新值后,您会看到该临时文件的破坏。

[*] 通常这应该包含 t 递增之前的值,但在您的实现中它只是递增后对象的拷贝,您通过执行 return 创建*这个;。所以你的函数体更适合operator++()(前自增)而不是operator++(int)(后自增)。

关于c++ - 析构函数之前工作。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7145914/

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