C++中继承 声明基类析构函数为虚函数作用,单继承和多继承关系的内存分布

时间:2021-10-08 14:50:15

1,基类析构函数不为虚函数

#include "pch.h"
#include <iostream> class CBase
{
public:
CBase() {
m_one = ;
printf("this is CBase construct\n");
}
~CBase() {
printf("this is ~CBase deconstruct\n");
} void setNumOne(int n)
{
m_one = n;
}
int getNumOne()
{
return m_one;
}
private:
int m_one;
}; class CDrived:public CBase
{
public:
CDrived() {
m_two = ;
printf("this is CDrived construct\n");
}
~CDrived() {
printf("this is ~CDrived deconstruct\n");
} void setNumTwo(int n)
{
m_two = n;
}
int getNumTwo()
{
return m_two;
}
private:
int m_two;
}; int main()
{
CBase *p = new CDrived;
delete p;
std::cout << "Hello World!\n";
}

输出:

this is CBase construct
this is CDrived construct
this is ~CBase deconstruct
Hello World!

可以发现继承类析构函数没有调用,若继承类中有一些资源需要释放,则不能释放,故需要将基类析构函数声明为虚函数。

 

#include "pch.h"
#include <iostream> class CBase
{
public:
CBase() {
m_one = ;
printf("this is CBase construct\n");
}
virtual ~CBase() {
printf("this is ~CBase deconstruct\n");
} void setNumOne(int n)
{
m_one = n;
}
int getNumOne()
{
return m_one;
}
private:
int m_one;
}; class CDrived:public CBase
{
public:
CDrived() {
m_two = ;
printf("this is CDrived construct\n");
}
~CDrived() {
printf("this is ~CDrived deconstruct\n");
} void setNumTwo(int n)
{
m_two = n;
}
int getNumTwo()
{
return m_two;
}
private:
int m_two;
}; int main()
{
CBase *p = new CDrived;
delete p;
std::cout << "Hello World!\n";
}

输出:

this is CBase construct
this is CDrived construct
this is ~CDrived deconstruct
this is ~CBase deconstruct
Hello World!

2,

#include "pch.h"
#include <iostream> class CBase
{
public:
CBase() {
m_one = ;
printf("this is CBase construct\n");
}
virtual ~CBase() {
printf("this is ~CBase deconstruct\n");
} virtual void setNumOne(int n)
{
m_one = n;
}
virtual int getNumOne()
{
return m_one;
}
private:
int m_one;
}; class CDrived:public CBase
{
public:
CDrived() {
m_two = ;
printf("this is CDrived construct\n");
}
~CDrived() {
printf("this is ~CDrived deconstruct\n");
} void setNumTwo(int n)
{
m_two = n;
}
int getNumTwo()
{
return m_two;
}
private:
int m_two;
}; int main()
{
CDrived *p = new CDrived;
printf("sizeof(CDrived) = %d\n", sizeof(CDrived)); //
delete p;
std::cout << "Hello World!\n";
}

C++中继承 声明基类析构函数为虚函数作用,单继承和多继承关系的内存分布

3,多继承

单继承只有一个虚表指针,而多继承往往有多个

#include "pch.h"
#include <iostream> class CFather
{
public:
CFather() { }
~CFather() { } virtual void setTall(int tall)
{
m_tall = tall;
} private:
int m_tall;
}; class CMother
{
public:
CMother() { }
~CMother() { } virtual void setWeight(int weight)
{
m_weight = weight;
} private:
int m_weight;
}; class CSon:public CFather,public CMother
{
public:
CSon() { }
~CSon() { } virtual void setAge(int age) // 地址存放在第一个虚表指针后面
{
m_age = age;
} private:
int m_age;
}; int main()
{
CSon cSon;
cSon.setAge();
printf("sizeof(CSon) = %d\n", sizeof(CSon)); // 20
std::cout << "Hello World!\n";
}

C++中继承 声明基类析构函数为虚函数作用,单继承和多继承关系的内存分布