首页 > 技术文章 > c++ 动态判断基类指针指向的子类类型(typeid)

ranson7zop 2017-12-01 10:01 原文

我们在程序中定义了一个基类,该基类有n个子类,为了方便,我们经常定义一个基类的指针数组,数组中的每一项指向都指向一个子类,那么在程序中我们如何判断这些基类指针是指向哪个子类呢?

本文提供了两种方法 (1) 自定义类id, (2)typeid

一、自定义id

如下所示基类father有两个子类son1 和 son2,我们在基类中定义类虚函数id,子类中分别重载了该函数,各个子类返回值都不同

class father
{
public:
    virtual void fun()
    {
        cout<<"this is father fun call\n";
    }
    virtual int id()
    {
        return 0;
    }
};

class son1: public father
{
public:

    void fun()
    {
        cout<<"this is the son1 fun call\n";
    }

    int id()
    {
        return 1;
    }

};

class son2: public father
{
public:

    void fun()
    {
        cout<<"this is the son2 fun call\n";
    }

    int id()
    {
        return 2;
    }
};

通过如下方法我们可以在程序中动态的判断基类指针指向的子类类型

int main()
{
    father * pf;
    son1 s1;
    son2 s2;
    pf = &s1;
    if(pf->id() == 1)
        cout<<"this is son1\n";
    else cout<<"this is son2\n";
}

二、typeid

typeid是c++的关键字,typeid操作符的返回结果是名为type_info的标准库类型的对象的引用(在头文件typeinfo中定义)

ISO C++标准并没有确切定义type_info,它的确切定义编译器相关的,但是标准却规定了其实现必需提供如下四种操作:

type_info类提供了public虚 析构函数,以使用户能够用其作为基类。它的默认构造函数和拷贝构造函数及赋值操作符都定义为private,所以不能定义或复制type_info类型的对象。

程序中创建type_info对象的唯一方法是使用typeid操作符(由此可见,如果把typeid看作函数的话,其应该是type_info的 友元)

type_info的name成员函数返回C-style的字符串,用来表示相应的类型名,但务必注意这个返回的类型名与程序中使用的相应类型名并不一定一致,这具体由编译器的实现所决定的,标准只要求实现为每个类型返回唯一的字符串

typeid 的参数可以使指针,可以使对象,可以是普通变量等。

具体判断基类指针指向的类型方法如下(类的定义同上):

int main()
{
    char sonstr[2][100];
    //由于不知道编译器对typeid.name返回的字符串,因此预先保存好返回的字符串
    strcpy(sonstr[0], typeid(son1).name());
    strcpy(sonstr[1], typeid(son2).name());
    father * pf;
    son1 s1;
    son2 s2;
    pf = &s1;
    if(strcmp(sonstr[0], typeid(*pf).name()) == 0)
    {
        cout<<"this is son1\n";
    }
    else if(strcmp(sonstr[1], typeid(*pf).name()) == 0)
    {
        cout<<"this is son2\n";
    }

    pf = &s2;
    if(strcmp(sonstr[0], typeid(*pf).name()) == 0)
    {
        cout<<"this is son1\n";
    }
    else if(strcmp(sonstr[1], typeid(*pf).name()) == 0)
    {
        cout<<"this is son2\n";
    }
    return 0;
}

【版权声明】转载请注明出处 http://www.cnblogs.com/TenosDoIt/p/3176525.html

推荐阅读