栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++虚析构函数、虚函数、虚继承

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++虚析构函数、虚函数、虚继承

一.来源

重点关注下面函数中内容!

void Test()
void func(A* ap)

例子:

class A {
public:
	A() {
		cout << "A()-----" << endl;
		this->p = new char[64];
		memset(this->p, 0, sizeof(this->p));
		strcpy_s(this->p,strlen("A string-----")+1 ,"A string-----");
	}
	virtual void print() {//虚函数
		cout << "A:" << this->p << endl;
	}
	~A() {
		cout << "~A()---------" << endl;
	}
private:
	char* p;
};
class B :public A {
public:
	B() {
		cout << "B()-----" << endl;
		this->p = new char[64];
		memset(this->p, 0, sizeof(this->p));
		strcpy_s(this->p, strlen("B string-----") + 1, "B string-----");
	}
	~B() {
		cout << "~B()---------" << endl;
	}
	virtual void print() {
		cout << "B:" << this->p << endl;
	}
private:
	char* p;
};
void func(A* ap)//父指针指向子类
{
	ap->print();
	delete ap;//释放内存空间
}
void Test() {
	A* a = new A;
	func(a);
}
int main() {
	Test();
}

结果:调用class A中的析构函数,这里没有问题。

下面修改函数:

void Test() {
	B* b = new B;
	func(b);
}

结果:这里出现问题了!调用的还是class A的析构函数,但是应该调用class B的析构函数!

因此,引出虚析构函数,产生多肽。

二.虚析构函数使用

注意下面各自定义,都是添加virtual。
虚函数:https://blog.csdn.net/weixin_44190648/article/details/122111016
虚继承:https://blog.csdn.net/weixin_44190648/article/details/122108830
在父类的析构函数前添加virtual。

class A {
public:
	A() {
		cout << "A()-----" << endl;
		this->p = new char[64];
		memset(this->p, 0, sizeof(this->p));
		strcpy_s(this->p,strlen("A string-----")+1 ,"A string-----");
	}
	virtual void print() {//虚函数
		cout << "A:" << this->p << endl;
	}
	virtual ~A() {//虚析构函数
		cout << "~A()---------" << endl;
	}
private:
	char* p;
};

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690191.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号