可能使用typeid确定父子关系 [英] Possible to Use typeid to Determine Parent-Child Relationship

查看:199
本文介绍了可能使用typeid确定父子关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有的时候,我使用dynamic_cast确定对象的父子关系。

all the while, I am using dynamic_cast to determine Parent-Child relationship of an object.

#include <iostream>

class A {
public:
    virtual ~A() {}
};

class B : public A {
};

class C : public A {
};

int main()
{
    B b;
    std::cout<< typeid(b).name()<< std::endl;       // class B

    A* a = dynamic_cast<A *>(&b);
    if (a) {
        std::cout<< "is child of A"<< std::endl;    // printed
    }

    C* c = dynamic_cast<C *>(&b);
    if (c) {
        std::cout<< "is child of C"<< std::endl;    // Not printed
    }
    getchar();
}

我可能知道我可以确定父子关系一个对象,通过typeid?例如,我怎么知道B是A的孩子,通过使用typeid检查?

May I know is it possible that I can determine parent-child relationship, of an object, through typeid? For example, how I can know B is the child of A, by using typeid checking?

谢谢。

推荐答案

我不认为你可以在当前的C + +使用 typeinfo 中的信息。我知道 boost :: is_base_of (Type Traits将是C ++ 0x的一部分):

I don't think you can do that in current C++ using the information in typeinfo only. I know of boost::is_base_of (Type Traits will be part of C++0x):

if ( boost::is_base_of<A, B>::value ) // true
{
    std::cout << "A is a base of B";
}

这篇关于可能使用typeid确定父子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆