C++基础(二十)虚析构函数、纯虚析构函数

话不多说上代码

#include <iostream>
using namespace std;

class Animal 
{
public:
	Animal() 
	{
		cout << "ani的构造器" << endl;
	}
	virtual void sayHello() = 0;
	string* m_name;
	//第一种写法  虚析构的写法
/*	virtual ~Animal() 
	{
		cout << "ani的析构函数" << endl;
	}
*/

//第一种写法  纯虚析构的写法 但这种写法必须提供具体实现
	virtual ~Animal() = 0;
};

Animal::~Animal() 
{
	cout << "ani的析构函数" << endl;
};


class Cat :public Animal 
{
public:
	Cat(string str) 
	{
		cout << "cat的构造器" << endl;
		m_name = new string(str);
	}
	virtual void sayHello() 
	{
		cout << *m_name<<"喵喵喵" << endl;
	}
	~Cat()
	{
		cout << "cat的析构函数" << endl;
		if(m_name!=NULL)
		{
			delete m_name;
			m_name = NULL;
		}
	}
};

void test01()
{
	Animal* ani = new Cat("godv");
	ani->sayHello();
	delete ani;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/we1less/article/details/108914128