这里的new Cat("Tom")是由于基类函数中的构造函数里面带有string变量
1. 法一:利用虚函数,虚化基类中的析构函数
virtual ~Animal()
{
cout << "动物的析构函数调用" << endl;
}2. 法二:利用纯虚函数,但要在类外有具体的函数实现,且无法实例化对象
#include<iostream> using namespace std; #include<string.h> class Animal { public: Animal() { cout << "动物的构造函数调用" << endl; } virtual void func() { cout << "动物在说话" << endl; } //法一:利用虚函数,虚化基类中的析构函数 //virtual ~Animal() //{ // cout << "动物的析构函数调用" << endl; //} //法二:利用纯虚函数,但要在类外有具体的函数实现,且无法实例化对象 virtual~Animal() = 0; }; Animal::~Animal() { cout << "动物的析构函数调用" << endl; } class Cat :public Animal { public: Cat(string name) { m_Name = new string(name); cout << "小猫的构造函数调用" << endl; } void func() { cout <<*m_Name<< "小猫在说话" << endl; } ~Cat() { cout << "cat的析构函数调用" << endl; } string* m_Name; }; void doWork(Animal* animal) { animal->func(); //如果父类中没有使用virtual来虚化析构,使地址不能晚绑定,此时的析构函数只会调用Anima类中的 delete animal; //下面这个是引用的方式 /*animal.func();*/ } void test01() { Animal* cat = new Cat("Tom"); doWork(cat); //Cat cat; //doWork(cat); } int main() { test01(); }
虚析构与纯虚析构
于 2024-04-30 19:47:06 首次发布