保证基类的也被调用。什么情况下使用比较好呢。

#include <iostream>
using namespace std;
class Base{
    private:
        int num1;
    public:
        Base():num1(10)
        {
        }
        virtual ~Base()
        {
            cout<<"base"<<endl;
        }
};
class Dervied:public Base{
    private:
        int num2;
    public:
        Dervied():num2(1)
        {
        }
        ~Dervied()
        {
            cout<<"Dervied"<<endl;
        }
};
int main()
{
    Base *pBase = new Dervied();
    delete pBase;
}

结果会
Dervied
Base
#include<iostream>
using namespace std;

class ClxBase
{
    public:
       ClxBase() {};
       ~ClxBase() {cout<<"Do base class destruct"<<endl;};

};

class ClxDerived : public ClxBase
{
    public:
       ClxDerived() {};
       ~ClxDerived() { cout << "Do derived class destruct!" << endl; };

};


int main()
{

    ClxBase *pTest = new ClxDerived;
    ClxDerived derived;

    delete pTest;

}
另一个例子输出的却是 :
Do base class destruct
Do derived class destruct!
Do base class destruct

说明了两个问题,只想派生类对象的基类指针需要基类声明虚系构函数才能调用派生类指针,而派生类对象却不用基类声明虚系构函数就能调用派生类指针


Posted on 2008-07-08 17:10 micheal's tech 阅读(279) 评论(0)  编辑 收藏 引用 所属分类: C++ programme language

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理