在以往的笔记中我们讲到过析构函数和虚函数。析构函数是释放被初始化的变量,虚函数是告诉编译器有重名的函数被复写去派生类找对应函数。
虚析构函数就是在基类析构函数前加入virtual表示派生类引用析构函数需要找派生类。看以下栗子。
#include <iostream>
class Base
{
publi:
Base(){std::cout<<Base Constructor<<std::endl;}
~Base(){std::cout<<Base Destructor<<std::endl;}
};
class Derived:public Base
{
public:
Derived(){std::cout<<Derived Constructor<<std::endl;}
~Derived(){std::cout<<Derived Destructor<<std::endl;}
};
int mian()
{
Base* base = new Base();
delete base;
std::cout<<"_____________________________________"<<std::endl;
Derived* derived= new Derived();
delete derived;
std::cout<<"_____________________________________"<<std::endl;
Base* ptr = new Derived();
delete ptr;
std::cout<<"_____________________________________"<<std::endl;
std::cin.get();
}
基类和派生类分别有自己的构造函数和析构函数,打印出的为
Base Constructor
Base Destructor
_____________________________________
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
_____________________________________
Base Constructor
Derived Constructor
Base Destructor
_____________________________________
我们来逐行解析main中代码,第一块创建Base基本类并删除base,打印对应构造与析构函数没有问题。
第二块创建Derived派生类,因为其基于Base所以需要将Base类初始化和析构一同执行,从打印结果也可以看出先执行基类构造、派生构造、派生析构、基类析构。
第三块代码什么问题,我们创建了Base类指针但实际上指向的是Derived类型指针(new是实际创建的,前面只是命名的)怎么解决呢?
#include <iostream>
class Base
{
publi:
Base(){std::cout<<Base Constructor<<std::endl;}
virtual ~Base(){std::cout<<Base Destructor<<std::endl;}
};
class Derived:public Base
{
public:
Derived(){std::cout<<Derived Constructor<<std::endl;}
~Derived(){std::cout<<Derived Destructor<<std::endl;}
};
int mian()
{
Base* base = new Base();
delete base;
std::cout<<"_____________________________________"<<std::endl;
Derived* derived= new Derived();
delete derived;
std::cout<<"_____________________________________"<<std::endl;
Base* ptr = new Derived();
delete ptr;
std::cout<<"_____________________________________"<<std::endl;
std::cin.get();
}
我们看到没有执行派生类的析构函数,所以我们在基类的析构函数前加上virtual使其变为虚函数。virtual意味着其存在的类存在派生类且析构函数可能会被调用,所以建立一个表供调用时查找。
Base是Derived的基类所以Derived就是Base,注意下类的范围。
Base Constructor
Base Destructor
_____________________________________
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
_____________________________________
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
_____________________________________
标签:函数,32,派生类,Derived,C++,Destructor,Base,Constructor,虚析构 From: https://blog.csdn.net/weixin_64418869/article/details/140754754