C++ 继承特性的小探讨——基类虚析构函数

本文探讨了C++中的继承特性,重点关注基类的虚析构函数。理解虚析构函数在多态中的作用,以及如何防止内存泄漏,对于C++程序员来说至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
说明: C++继承特性的一些测试
1. 构造函数的调用,发生在创建时,而不是声明时
2. 使用继承,有必要将基类析构函数定义为虚函数(否则将只调用所声明类(一般是基类)的析构函数,这样是不安全的)
3. 若基类某成员方法或析构函数被定义为虚函数,则其派生类相应的成员方法自动变为虚函数(即声明为可以被覆写),此时
派生类中virtual关键字可以加也可以不加(若需要告诉下级派生类,该方法可以被覆盖,往往显式加virtual关键字)。
4. 派生类对基类公有继承,则只能在本派生类内部访问基类protected类型成员(但派生类本质上拥有基类private成员,只是没有访问权)
对public类型成员则无限制
5. 程序效果可以通过分别注释PerSon类中带和不带virtual关键字的析构函数,运行看结果
*/
#include <iostream>
using namespace std;

class Person
{
protected:
	int m_identity;
public:
	virtual void TellIdentity() = 0;
public:
	Person();
	virtual ~Person();		//基类析构函数用virtual关键字修饰
	//~Person();			//基类析构函数不用virtual关键字修饰
};

class Student :public Person
{
public:
	void TellIdentity();
public:
	Student();
	~Student();
};

class ColledgeStudent :public Student
{
private:
	int m_iCET4Score;
public:
	void TellIdentity();
public:
	ColledgeStudent();
	~ColledgeStudent();
};

Person::Person()
{
	m_identity = 100;
	cout << "PersonClass Constructed." << endl;
}

Person::~Person()
{
	cout << "PersonClass Distructed." << endl;
}

Student::Student()
{
	cout << "StudentClass Constructed." << endl;
}

Student::~Student()
{
	cout << "StudentClass Distructed." << endl;
}

void Student::TellIdentity()
{
	cout << "StudentNum is " << m_identity << endl;
}

ColledgeStudent::ColledgeStudent()
{
	m_iCET4Score = 460;
	cout << "ColledgeStudentClass Constructed." << endl;
}

ColledgeStudent::~ColledgeStudent()
{
	cout << "ColledgeStudentClass Distructed." << endl;
}

void ColledgeStudent::TellIdentity()
{
	cout << "StudentNum is " << m_identity << endl;
	cout << "CET4Score is " << m_iCET4Score << endl;
}

int main()
{
	Person *pPer; 
	pPer = new Student;
	pPer->TellIdentity();
	delete pPer;
	cout << "------------------分割线-----------------" << endl;
	pPer = new ColledgeStudent();
	pPer->TellIdentity();
	delete pPer;
	pPer = 0;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值