pro*_*eve 4 c++ destructor visual-c++
#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");
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是:
DES
1Press any key to continue...
DES
DES
Run Code Online (Sandbox Code Playgroud)
为什么析构函数之前有效?
表达式t++导致类型的临时对象test,因为operator++(int)返回值[*].在operator=完成使用它来分配新值之后,你会看到那个临时的破坏t1.
[*]通常这应该包含t它递增之前的值,但是在你的实现中它只是递增后的对象的副本,你通过这样做来创建return *this;.所以你的函数体更适合operator++()(预增量)而不是operator++(int)(后增量).
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |