RTTI的魅力(运行时类型识别 Run-time type Identification)

来源:互联网 发布:椭圆拟合编程 编辑:程序博客网 时间:2024/05/16 08:58

一句话总结:实际运行时检查指针或者引用指向的实际派生类型。

两个重要的哼哈二将:typeid、dynamic_cast

#ifndef CRTTI_hpp

#define CRTTI_hpp


#include <iostream>


class CPerson

{

public:

    void getup(){std::cout<<"getup..."<<std::endl;}

    void sleep(){std::cout<<"sleep..."<<std::endl;}

    virtual ~CPerson(){}//这个很重要,没有这个,RTTI就不要玩了

public:

    int age;

    int tall;

};


class CFarmer: publicCPerson

{

public:

    void farming(){std::cout<<"farming..."<<std::endl;};

};


class CWorker: publicCPerson

{

public:

    void building(){std::cout<<"building..."<<std::endl;};

};


#endif /* CRTTI_hpp */



#include <iostream>

#include "CRTTI.hpp"

using namespacestd;


void doAction(CPerson* obj)

{

    cout<<typeid(*obj).name()<<endl;

    obj->getup();

    if (typeid(*obj) ==typeid(CFarmer)) {

        CFarmer* farmer =dynamic_cast<CFarmer*>(obj);

        farmer->farming();

    }

    else{

        cout<<"who are you"<<endl;

    }

    obj->sleep();

}


int main(int argc,constchar * argv[]) {

    // insert code here...

    CFarmer farmer;

    doAction(&farmer);

    CWorker *worker =newCWorker();

    doAction(worker);

    delete worker;

    return0;

}


运行结果:

7CFarmer

getup...

farming...

sleep...

7CWorker

getup...

who are you

sleep...

Program ended with exit code: 0


dynamic_cast注意事项:
1、只能应用于指针和引用之间的转换
2、要转换的类型中必须包含虚函数
3、转换成功返回子类的地址,失败返回null


typeid注意事项:
1、type_id返回一个type_info对象的引用
2、基类必须带有虚函数,否则通过基类获得的数据类型依旧是基类




阅读全文
0 0