📜  C++中的std :: has_virtual_destructor以及示例

📅  最后修改于: 2021-05-30 14:04:40             🧑  作者: Mango

C++ STL的std :: has_virtual_destructor用于检查给定的类型T是否具有虚拟的析构函数。它返回布尔值true或false。以下是相同的语法:

头文件:

#include

句法:

template
  
  struct has_virtual_destructor;

参数:模板std :: has_virtual_destructor接受单个参数T(Trait类)以检查T是否具有虚拟析构函数。

返回值:

  • 正确:如果存在虚拟析构函数。
  • False:如果虚拟析构函数不存在。

下面的程序说明了C++ STL中的std :: has_virtual_destructor模板:

程序1:

// C++ program to illustrate
// has_virtual_destructor example
  
#include 
#include 
using namespace std;
  
struct gfg1 {
};
struct gfg2 {
    virtual ~gfg2() {}
};
struct gfg3 : gfg2 {
};
  
// Driver Code
int main()
{
    cout << boolalpha;
    cout << "has_virtual_destructor:"
         << endl;
    cout << "int: "
         << has_virtual_destructor::value
         << endl;
    cout << "gfg1: "
         << has_virtual_destructor::value
         << endl;
    cout << "gfg2: "
         << has_virtual_destructor::value
         << endl;
    cout << "gfg3: "
         << has_virtual_destructor::value
         << endl;
  
    return 0;
}
输出:
has_virtual_destructor:
int: false
gfg1: false
gfg2: true
gfg3: true

程式2:

// C++ program to illustrate
// has_virtual_destructor example
  
#include 
#include 
using namespace std;
  
struct gfg1 {
    virtual ~gfg1() {}
};
struct gfg2 {
};
struct gfg3 : gfg1 {
};
  
// Driver Code
int main()
{
    cout << boolalpha;
    cout << "has_virtual_destructor:"
         << endl;
    cout << "int: "
         << has_virtual_destructor::value
         << endl;
    cout << "gfg1: "
         << has_virtual_destructor::value
         << endl;
    cout << "gfg2: "
         << has_virtual_destructor::value
         << endl;
    cout << "gfg3: "
         << has_virtual_destructor::value
         << endl;
  
    return 0;
}
输出:
has_virtual_destructor:
int: false
gfg1: true
gfg2: false
gfg3: true

参考: http://www.cplusplus.com/reference/type_traits/has_virtual_destructor/

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”