C++ - 覆盖期间调用析构函数时的类成员
我试图理解覆盖对象时构造函数和析构函数调用的顺序。
我的代码是:
class A
{
public:
A(int n): x(n)
{ cout << "A(int " << n << ") called" << endl; }
~A( )
{ cout << "~A( ) with A::x = " << x << endl; }
private:
int x;
};
int main( )
{
cout << "enter main\n";
int x = 14;
A z(11);
z = A(x);
cout << "exit main" << endl;
}
--
输出是:
enter main
A(int 11) called
A(int 14) called
~A( ) with A::xx = 14
exit main
~A( ) with A::xx = 14
--
为什么调用析构函数时 A::xx = 14 ?不应该是11吗?
im trying to understand the order of Constructor and Destructor calls when overwriting an object.
My code is :
class A
{
public:
A(int n): x(n)
{ cout << "A(int " << n << ") called" << endl; }
~A( )
{ cout << "~A( ) with A::x = " << x << endl; }
private:
int x;
};
int main( )
{
cout << "enter main\n";
int x = 14;
A z(11);
z = A(x);
cout << "exit main" << endl;
}
--
The output is :
enter main
A(int 11) called
A(int 14) called
~A( ) with A::xx = 14
exit main
~A( ) with A::xx = 14
--
Why is A::xx = 14 when the destructor is called? Shouldn't it be 11?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么应该是11?您将
z
重新分配给A(14)
,因此最后是 14。(编辑后:您还会看到临时
A(14)
对象的析构函数,该对象在赋值结束时被销毁。)Why should it be 11? You reassign
z
toA(14)
, so it's 14 at the end.(After your edit: You also see the destructor of the temporary
A(14)
object that gets destroyed at the end of the assignment.)