虚析构和纯虚析构

 

虚析构和纯虚析构

虚析构和纯虚析构 

 虚析构和纯虚析构

#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;
}
上一篇:No compiler is provided in this environment Perhaps you are


下一篇:cmd中mvn命令,出现No compiler is provided in this environment. Perhaps you are running on a JRE rather tha