c++动态类型识别

动态类型指基类指针所指向的对象的实际类型
child*c=(child*)p //若p动态类型为parent,可能出现无法预知错误
基类指针是否可以强制类型转换为子类指针取决于动态类型
——/根据多态
class Parent
{
public:
    enum { ID = 0 };
    virtual int type()
    {
        return ID;
    }
};

class Child : public Parent
{
public:
    enum { ID = 1 };
    int type()
    {
        return ID;
    }
};

void test(Parent* p)
{
    if( p->type() == Child::ID )
    {
        Child* c = (Child*)p;
        cout<<"Dynamic Type: "<<"Child"<<endl;
    }
    if( p->type() == Parent::ID )
    {
        cout<<"Dynamic Type: "<<"Parent"<<endl;
    }
}

int main()
{
    Parent parent;
    Child child;
    test(&parent);
    test(&child);
    return 0;
}
——/
使用多态进行动态类型识别缺陷(维护性很差):
①须从基类提供类型虚函数②所有派生类须重写类型虚函数③每个派生类类型ID须唯一
class Parent
{
public:
	virtual ~Parent(){}  //工程中常如此
};

class Child : public Parent
{
};

class NewChild : public Parent 
{
};

void test(Parent* p)
{
    Child* c = dynamic_cast<Child*>(p);
    if( c != NULL )
    {
        cout<<"Child"<<endl;
    }
    else
    {
        if( dynamic_cast<NewChild*>(p) != NULL )
        {
            cout<<"NewChild"<<endl;
        }
        else
        {
            cout<<"Parent"<<endl;
        }
    }
}

int main()
{
    Parent parent;
    Child child;
    NewChild nc;
    test(&parent);
    test(&child);
    test(&nc);
    return 0;
}
结果:Parent Child NewChild
如缺virtual ~Parent(){},报source type is not polymorphic错,因:
dynamic_cast主用于基类派生类间转换,要求目标对象类型为多态
用于指针转换,转换失败返回空;用于引用转换,转换失败引发bad_cast异常
——/动态获得任意变量类型信息
dynamic_cast缺陷:只能用于具有虚函数的类族(工程上常把析构函数定义为虚函数)
typeid关键字用于动态获取类型信息,返回一type_info类对象
typeid参数为NULL,抛出bad_typeid异常,包含<typeinfo>
class Parent
{
public:
	virtual ~Parent(){}
};

class Child : public Parent{};

void test(Parent* p)
{
    if( typeid(*p) == typeid(Child) )
    {
        cout<<"Child"<<endl;
    }
    else if( typeid(*p) == typeid(Parent) )
    {
        cout<<"Parent"<<endl;
    }
}

int main()
{
    Parent parent;
    Child child;
    int index;
    char ch;
    
    const type_info& tp = typeid(parent);
    const type_info& tc = typeid(child);
    const type_info& ti = typeid(index);
    const type_info& tch = typeid(ch);
    cout<<tp.name()<<endl;  
    cout<<tc.name()<<endl;
    cout<<ti.name()<<endl;
    cout<<tch.name()<<endl;
    test(&parent);
    test(&child);
	
    return 0;
}
结果:6Parent 5Child I c Parent Child
若无virtual ~Parent(){},结果Parent Parent
——/
可通过多态或dynamic_cast关键字或typeid关键字进行动态类型识别
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值