首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么在c++中动态获得对象的名称

2013-05-02 
如何在c++中动态获得对象的名称代码如下class A{}class B:public A{}class C:public A{}int main(){A *obj

如何在c++中动态获得对象的名称
代码如下



class A
{

}

class B:public A
{


}

class C:public A
{


}

int main()
{

A *object = new B();

//some function to show object's name?

}






B,C是A的派生类,有没有什么办法能够从父类A类的object对象,获得指向子类对象的名字?

现在我只能这么做



class A
{
virtual void showname(){cout<<"I am A"<<endl;}
}

class B:public A
{
virtual void showname(){cout<<"I am B"<<endl;}
}

class C:public A
{
virtual void showname(){cout<<"I am C"<<endl;}
}

int main()
{

A *object = new B();
object->showname();

}



不过这样的话在每一个类里面,都需要写对于基类虚函数showname的重写,似乎太笨拙。。。所以想询问又没有什么好一点的方法可以解决这个问题。。。
C++ 类 对象 虚函数
[解决办法]
typeid(*object).name()
[解决办法]
typeid Operator
C++ Specific —>

typeid( type-id )

typeid( expression )

The typeid operator allows the type of an object to be determined at run-time.

The result of a typeid expression is a const type_info&. The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used. See type_info Class for more information.

END C++ Specific

热点排行