虚函数(构造函数+析构函数)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
虚函数(构造函数+析构函数)
构造函数不能时虚函数.创建派⽣类对象时,将调⽤派⽣类的构造函数,⽽不是基类的构造函数,然后,派⽣类的构造函数将使⽤基类的⼀个构造函数,这种顺序不同于继承机制.
因此,派⽣类不继承基类的构造函数,所以将类构造函数声明为虚函数⽆意义.
析构函数应当是虚函数,除⾮类不⽤做基类.
默认的称作"静态联编".
// 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;
return0;
}
}
通常应给基类提供⼀个虚析构函数,即使它并不需要析构函数.
构造函数和析构函数⾥⾯不能调⽤其他虚函数,即使调⽤,也失去了虚函数的意义. C++的对象动态⽣成机制.。