C++中实现类似instanceof的方法

描述

前言

C++有多态与继承,但是很多人开始学习C++,有时候会面临一个常见问题,就是如何向下转型,特别是不知道具体类型的时候,这个时候就希望C++ 可以向Java或者Python中有instanceof这个函数,可实际上C++中没有。但是别着急,其实C++中有两种简单的方法可以实现类似Java中的instanceof的功能。  

在 C++ 中,确定对象的类型是编程中实际需求,使开发人员能够做出动态决策并执行特定于类型的操作。无论是在编译时检查类型,还是在运行时动态标识对象类型,C++ 都提供了强大的机制来获取类型信息

使用typeid.name()方法

寻找实例的类类型,代码演示如下:

C++

使用std::is_same方法

代码实现与运行效果如下:

C++

使用dynamic_cast 

dynamic_cast方法转型是C++中一种非常杰出的方法。通过dynamic_cast操作符允许跨类层次结构动态转换指针和引用,从而在运行时确认和转换类型。代码演示如下:

C++

完整测试源代码

 1#include 
 2#include 
 3#include 
 4
 5using namespace cv;
 6using namespace std;
 7
 8class Vehicles {
 9public:
10    string make;
11    string model;
12    string year;
13};
14
15class Aircraft {
16public:
17    string make;
18    string model;
19    string year;
20};
21
22template 
23void printType() {
24    if (std::is_same::value) {
25        std::cout << "Type is Aircraft" << std::endl;
26    }
27    else if (std::is_same::value) {
28        std::cout << "Type is Vehicles" << std::endl;
29    }
30    else {
31        std::cout << "Type is unknown" << std::endl;
32    }
33}
34
35class Base {
36public:
37    virtual ~Base() {}  // Adding a virtual destructor for polymorphism
38};
39class Derived : public Base {
40    // Class definition
41};
42int main(int argc, char** argv) {
43    Base baseObj;
44    Derived derivedObj;
45    Base* ptrBase = &derivedObj;
46    Derived* ptrDerived = dynamic_cast(ptrBase);
47    if (ptrDerived) {
48        std::cout << "Object is of type Derived" << std::endl;
49    }
50    else {
51        std::cout << "Object is not of type Derived" << std::endl;
52    }
53
54
55
56    Vehicles car;
57    Aircraft craft;
58    const char* name1 = typeid(car).name();
59    const char* name2 = typeid(craft).name();
60    std::cout << "object name: " << name1 << std::endl;
61    std::cout << "object name: " << name2 << std::endl;
62
63    printType();
64    printType();
65
66    return 0;
67}

 

 

 

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分