using namespace std;
class Base
{
public:
/* virtual */ ~Base() { cout << "Base::~Base" << endl; }
Base() { cout << "Base::Base" << endl; }
};
class Third : public Base
{
public:
~Third() { cout << "Third::~Third" << endl; }
Third() { cout << "Third::Third" << endl; }
};
int main(int argc, char **argv)
{
cout << "Constructure Third:" << endl;
Base *t = new Third;
cout << "Constructure Third:" << endl;
Third *q = new Third;
cout << "Deconstructure Third:" << endl;
delete q;
cout << "Deconstructure Third:" << endl;
delete t;
return 0;
}
[flydream@flydream C++]$
[flydream@flydream C++]$ ./a.out
Constructure Third:
Base::Base
Third::Third
Constructure Third:
Base::Base
Third::Third
Deconstructure Third:
Third::~Third
Base::~Base
Deconstructure Third:
Base::~Base
如果在基类的析构函数中加上VIrtual则结果为
[flydream@flydream C++]$ ./a.out
Constructure Third:
Base::Base
Third::Third
Constructure Third:
Base::Base
Third::Third
Deconstructure Third:
Third::~Third
Base::~Base
Deconstructure Third:
Third::~Third
Base::~Base
C++中的虚函数和纯虚函数用法
1.虚函数和纯虚函数可以定义在同一个类(class)中,含有纯虚函数的类被称为抽象类(abstractclass),而只含有虚函数的类(class)不能被称为抽象类(abstractclass)。
2.虚函数可以被直接使用,也可以被子类(subclass)重载以后以多态的形式调用,而纯虚函数必须在子类(subclass)中实现该函数才可以使用,因为纯虚函数在基类(baseclass)
只有声明而没有定义。
3.虚函数和纯虚函数都可以在子类(subclass)中被重载,以多态的形式被调用。
4.虚函数和纯虚函数通常存在于抽象基类(abstractbase class-ABC)之中,被继承的子类重载,目的是提供一个统一的接口。
5.虚函数的定义形式:virtual {method body};纯虚函数的定义形式:virtual { } = 0;在虚函数和纯虚函数的定义中不能有static标识符,原因很简单,被static修饰的函数在编译时候要求前期bind,然而虚函数却是动态绑定(run-timebind),而且被两者修饰的函数生命周期(life recycle)也不一样。