其他分享
首页 > 其他分享> > 虚析构和纯虚析构

虚析构和纯虚析构

作者:互联网

 

 

 

#include<iostream>
#include<string>
using namespace std;
class Animal
{
public:
	Animal()
	{
		cout << "animal 的构造" << endl;
	}
	virtual void Speak() = 0;
	//子类不写析构函数也不会报错,可能因为子类有默认析构函数;
	virtual ~Animal() = 0;
};
//纯虚析构必须在类外写具体的函数实现;
Animal::~Animal()
{
	cout << "animal 的析构函数" << endl;
}

class Cat :public Animal
{
public:
	Cat(string name)
	{
		cout << "cat 的构造函数" << endl;
		m_Name = new string(name);  //在堆区开辟空间存储name,并用指针管理;
	}

	void Speak() {
		cout <<*m_Name<< "cat is speak:" << endl;
	}
	~Cat()
	{
		delete m_Name;   //释放堆区自己开辟的name存储空间;
		cout << "cat 析构函数" << endl;
	}

	string* m_Name;
};
int main() 
{
	Animal* cat = new Cat("Tom");
	cat->Speak();
	delete cat;

	system("pause"); 
	return 0;
}

标签:std,Speak,return,纯虚析构,Animal,include,虚析构,delete
来源: https://blog.csdn.net/weixin_46432495/article/details/121880501