为什么必须实现虚析构函数 ,纯虚析构函数的原因

本文的主要参考书籍是  C++ Primer

struct A { 
	virtual ~A() = 0;
	 }; 
	struct B : A {
	 virual ~B() {} 
}; 
	int main( void ) {
 	B x; 
} 


编译的时候肯定报A::~A未实现,这是因为普通virtual只调用动态类型的那个函数实现,所以基类的可以不实现;而virtual析构函数则不同,它需要由下往上层层调用,所以每一层都需要实现。 另外,有没有实现代码 跟 是否为纯虚 是没有关系的,只要把 A 改为: struct A { virtual ~A() = 0 {} };

看看下面的解释:

A destructor can be declared virtual(10.3) or pure virtual(10.4);if any object of that class or any derived class are created in the program, the destructor shall be defined. If a class has a base class with a virtual destructor, its destructor (whether user-or implicitly-declared) is virtual. 

struct A 
{ 
virtual ~A() = 0 {} 
}; 
应当写成 
struct A 
{ 
virtual ~A() = 0; 
}; 
A::~A() 
{ 
} 
 

因为C++规定 =0 和 {} 不能同时出现。

[Note: a function declaration cannot provide both a pure-specifier and a definition 
—end note] 
[Example: 
struct C { 
virtual void f() = 0 { }; // ill-formed 
}; 
—end example]  

必须实现虚析构函数 ,纯虚析构函数的原因 大致如上!


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值