C++中的纯虚析构函数

当使用基类指针对象销毁派生类的实例时,虚拟析构函数用于释放派生类对象或实例分配的内存空间。

null

注: 只有析构函数可以是虚拟的。构造函数不能声明为虚拟的。

纯虚析构函数

可以声明纯虚拟析构函数。将析构函数创建为纯虚拟对象后,必须提供析构函数体。这是因为在派生类中不会重写析构函数,而是会以相反的顺序调用。因此,对于纯虚拟析构函数,必须指定析构函数体。

在C++中析构函数是否可以是纯虚函数?

是的,有可能有一个纯虚拟析构函数。纯虚析构函数在标准C++中是合法的,并且最重要的一件事是记住,如果一个类包含一个纯虚析构函数,它必须为纯虚析构函数提供一个函数体。

为什么纯虚函数需要函数体?

原因是析构函数(与其他函数不同)实际上并没有被“重写”,而是总是以与类派生相反的顺序调用它们。这意味着将首先调用派生类的析构函数,然后调用基类析构函数。如果没有提供纯虚拟析构函数的定义,那么在对象销毁期间将调用什么函数体?因此,编译器和链接器强制执行纯虚拟析构函数的函数体的存在。

考虑下面的程序:

CPP

// CPP Program to demonstrate pure virtual destructor
#include <iostream>
using namespace std;
class Base {
public :
virtual ~Base() = 0;
// Pure virtual destructor
};
class Derived : public Base {
public :
~Derived() { cout << "~Derived() is executed" ; }
};
// Driver Code
int main()
{
Base* b = new Derived();
delete b;
return 0;
}


链接器将在上述程序中产生以下错误。

test.cpp:(.text$_ZN7DerivedD1Ev[__ZN7DerivedD1Ev]+0x4c): undefined reference to `Base::~Base()' 

现在,如果提供了纯虚拟析构函数的定义,那么程序编译并运行良好。

CPP

#include <iostream>
class Base {
public :
virtual ~Base() = 0; // Pure virtual destructor
};
Base::~Base()
{
std::cout << "Pure virtual destructor is called" ;
}
class Derived : public Base {
public :
~Derived() { std::cout << "~Derived() is executed" ; }
};
int main()
{
Base* b = new Derived();
delete b;
return 0;
}


输出

~Derived() is executedPure virtual destructor is called

需要注意的是,当一个类包含一个纯虚析构函数时,它就变成了一个抽象类。例如,尝试编译以下程序,

CPP

#include <iostream>
class Test {
public :
virtual ~Test() = 0;
// Test now becomes abstract class
};
Test::~Test() {}
// Driver Code
int main()
{
Test p;
Test* t1 = new Test;
return 0;
}


上述程序编译失败并显示以下错误消息。

[Error] cannot declare variable 'p' to be of abstract type 'Test' [Note] because the following virtual functions are pure within 'Test': [Note] virtual Test::~Test() [Error] cannot allocate an object of abstract type 'Test' [Note] since type 'Test' has pure virtual functions

相关文章:

本文由 见见普拉瓦西 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享