C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ 虚拟析构

C++中的析构函数是用于释放由其占用的空间或删除其对象的类的成员函数。超出范围的类。析构函数的名称与类中构造函数的名称相同,但析构函数在其函数名称之前使用波浪号(〜)。

虚拟析构函数

虚拟析构函数用于释放派生类对象或实例分配的内存空间,同时使用基类指针对象删除派生类的实例。基类或父类的析构函数使用 virtual 关键字来确保基类和派生类的析构函数都将在运行时被调用,但它先调用派生类,然后再调用基类以释放占用的空间

为什么我们在C++中使用虚拟析构函数?

当类中的对象超出范围或执行main()函数时即将结束时,将自动在程序中调用析构函数,以释放该类的析构函数所占用的空间。当删除指向派生类的基类的指针对象时,由于编译器的早期绑定,仅调用父类析构函数。这样,它将跳过对派生类的析构函数的调用,从而导致程序中出现内存泄漏问题。而且,当我们在基类中使用虚拟关键字,并在其前面带有析构符tilde(〜)符号时,它可以确保首先调用派生类的析构函数。然后调用基类的析构函数以释放继承类中两个析构函数占用的空间。

编写程序以显示类析构函数的未定义行为,而无需在C中使用虚拟析构函数++。

#include<iostream>
using namespace std;
class Base
{                            
    public: /* A public access specifier defines Constructor and Destructor function to call by any object in the class. */
    Base() // Constructor function. 
{
    cout<< "\n Constructor Base class";
}
 ~Base() // Destructor function 
{
    cout<< "\n Destructor Base class";
}
};
class Derived: public Base
{
    public: /* A public access specifier defines Constructor and Destructor function to call by any object in the class. */
    Derived() // Constructor function 
{
    cout << "\n Constructor Derived class" ;
}
 ~Derived() // Destructor function 
{
    cout << "\n Destructor Derived class" ; /* Destructor function is not called to release its space. */
}       
};
int main()
{
    Base *bptr = new Derived; // Create a base class pointer object 
       delete bptr; /* Here pointer object is called to delete the space occupied by the destructor.*/
}  
输出:
C++中的虚拟析构函数
正如我们在上面的输出中看到的那样,当编译器编译代码时,它会在引用基类的main函数中调用一个指针对象。因此,它执行基类的Constructor()函数,然后移至派生类的Constructor()函数。之后,它将删除由基类的析构函数和派生类的析构函数占用的指针对象。基类指针仅删除基类的析构函数,而不在程序中调用派生类的析构函数。因此,它会泄漏程序中的内存。
注意: 如果基类析构函数不使用虚拟关键字,则由于指针对象指向基类,因此仅基类析构函数将被调用或删除其占用的空间。因此,它不会调用派生类析构函数来释放派生类使用的内存,这会导致派生类的内存泄漏。

编写程序以使用C++中的虚拟析构函数来显示类析构函数的行为。

#include<iostream>
using namespace std;
class Base
{
    public:
    Base() // Constructor member function.  
{
    cout << "\n Constructor Base class";  // It prints first.
}
 virtual ~Base() // Define the virtual destructor function to call the Destructor Derived function.
{
    cout << "\n Destructor Base class";  /
}
};
// Inheritance concept
class Derived: public Base 
{
    public:
    Derived() // Constructor function.
{
    cout << "\n Constructor Derived class" ; /* After print the Constructor Base, now it will prints. */
}
 ~Derived() // Destructor function 
{
    cout << "\n Destructor Derived class"; /* The virtual Base Class? Destructor calls it before calling the Base class Destructor. */
}       
};
int main()
{
    Base *bptr = new Derived; // A pointer object reference the Base class.
    delete bptr; // Delete the pointer object.
}
输出:
C++中的虚拟析构函数
在上面的程序中,我们在基类中使用了虚拟析构函数,该虚构的析构函数在调用基类的析构函数之前先调用派生类的析构函数,然后释放空间或解决程序中的内存泄漏问题。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4