s****l 发帖数: 41 | 1 #include
class A
{
public:
A(int n = 2) : m_i(n) { }
~A() { std::cout << m_i; }
protected:
int m_i;
};
class B
: public A
{
public:
B(int n) : m_x(m_i + 1) , m_a(n) { }
public:
~B()
{
std::cout << m_i;
--m_i;
}
private:
A m_x;
A m_a;
};
int main()
{
{ B b(5); }
std::cout << std::endl;
return 0;
}
为什么输出为 2531? |
l*********s 发帖数: 5409 | 2 sequence of detor calling is the reverse of sequence of ctor calling. ctor
calling follows the order first base class, then the member variables |
p*a 发帖数: 592 | 3 先call B的destructor,打印2,然后call m_a的,打印5,然后call m_x的,打印3,
最后call B的父亲A的dtor,打印1,因为m_i已经被--过了。
【在 s****l 的大作中提到】 : #include : class A : { : public: : A(int n = 2) : m_i(n) { } : ~A() { std::cout << m_i; } : protected: : int m_i; : }; : class B
|