码迷,mamicode.com
首页 > 其他好文 > 详细

虚函数(构造函数+析构函数)

时间:2015-08-13 13:41:05      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

构造函数不能时虚函数.创建派生类对象时,将调用派生类的构造函数,而不是基类的构造函数,然后,派生类的构造函数将使用基类的一个构造函数,这种顺序不同于继承机制.

因此,派生类不继承基类的构造函数,所以将类构造函数声明为虚函数无意义.

 

析构函数应当是虚函数,除非类不用做基类.

默认的称作"静态联编".

// HeritedDerived.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include <iostream>
using namespace std;

class Father
{
public:
    Father()
    {
        cout << "I am father!\n";
    }
    virtual ~Father()
    {
        cout << "this is father‘s destructor!\n";
        Compare();
    
    }

    virtual void Output()
    {
        cout << "This is a debug function in father\n";
    }

    virtual void Compare()
    {
        cout << "This is another virtual function in father\n";
    }
    
};

class Son : public Father
{
public:
    Son()
    {
        cout << "I am Son!\n";
        m_pInt = new int[32];

    }
    ~Son()
    {
        cout << "this is son‘s destructor!\n";
        if (NULL != m_pInt)
        {
            delete[] m_pInt;
            m_pInt = NULL;
            cout <<"Memory release successfully!\n";

        }
        Compare();
    }

    virtual void Output()
    {
        cout << "This is a debug function in son\n";
    }
    virtual void Compare()
    {
        cout << "This is another virtual function in son\n";
    }

private:
    int* m_pInt;

};
int _tmain(int argc, _TCHAR* argv[])
{

    Father father;
    Son son;
    son.Output();
    Father *father1 = new Son;
    father1->Output();
    delete father1;

    return 0;
}

}

通常应给基类提供一个虚析构函数,即使它并不需要析构函数.

 

构造函数和析构函数里面不能调用其他虚函数,即使调用,也失去了虚函数的意义. C++的对象动态生成机制.

 

虚函数(构造函数+析构函数)

标签:

原文地址:http://www.cnblogs.com/gycui/p/4726819.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!