我试图在覆盖对象时理解构造函数和析构函数调用的顺序。
我的代码是:
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?
答案 0 :(得分:2)
为什么要11岁?您将z
重新分配给A(14)
,最后是14。
(编辑之后:您还会看到在作业结束时被销毁的临时A(14)
对象的析构函数。)