继承关系下构造析构顺序
#include<iostream>
using namespace std;
class Base
{
public:
Base(){
cout << "Base ctor ..." << endl;
}
virtual ~Base(){
cout << "Base dtor ..." << endl;
}
};
class Derived:public Base
{
public:
Derived(){
cout << "Derived ctor ..." << endl;
}
~Derived(){
cout << "Derived dtor ..." << endl;
}
};
int main()
{
Derived test;
return 0;
}
程序运行结果:
Base ctor ...
Derived ctor ...
Derived dtor ...
Base dtor ...
复合关系下的构造和析构
#include<iostream>
using namespace std;
class Component
{
public:
Component(){
cout << "Component ctor ..." << endl;
}
~Component(){
cout << "Component dtor ..." << endl;
}
};
class Container
{
public:
Container(){
cout << "Container ctor ..." << endl;
}
~Container(){
cout << "Container dtor ..." << endl;
}
Component c;
};
int main()
{
Container foo;
return 0;
}
程序执行结果:
Component ctor ...
Container ctor ...
Container dtor ...
Component dtor ...
继承和复合关系下的构造和析构
#include<iostream>
using namespace std;
class Component
{
public:
Component(){
cout << "Component ctor ..." << endl;
}
~Component(){
cout << "Component dtor ..." << endl;
}
};
class Base
{
public:
Base(){
cout << "Base ctor ..." << endl;
}
virtual ~Base(){
cout << "Base dtor ..." << endl;
}
int n;
};
class Derived:public Base
{
public:
Derived(){
cout << "Derived ctor ..." << endl;
}
~Derived(){
cout << "Derived dtor ..." << endl;
}
Component c;
};
int main()
{
Derived foo;
return 0;
}
程序执行结果:
Base ctor ...
Component ctor ...
Derived ctor ...
Derived dtor ...
Component dtor ...
Base dtor ...
#include<iostream>
using namespace std;
class Component
{
public:
Component(){
cout << "Component ctor ..." << endl;
}
~Component(){
cout << "Component dtor ..." << endl;
}
};
class Base
{
public:
Base(){
cout << "Base ctor ..." << endl;
}
virtual ~Base(){
cout << "Base dtor ..." << endl;
}
Component c;
};
class Derived:public Base
{
public:
Derived(){
cout << "Derived ctor ..." << endl;
}
~Derived(){
cout << "Derived dtor ..." << endl;
}
};
int main()
{
Derived foo;
return 0;
}
程序执行结果:
Component ctor ...
Base ctor ...
Derived ctor ...
Derived dtor ...
Base dtor ...
Component dtor ...
文章不错支持一下吧