以编程方式获取派生类的名称 [英] Programmatically getting the name of a derived class
问题描述
我正在尝试做类似的事情:
I am attempting to do something like:
class Base {
public:
Base() {
cout << typeid(*this).name() << endl;
}
...
};
class Derived : public Base { ... }
class MoreDerived : public Derived { ... }
Derived d;
MoreDerived m;
问题是,当我需要查看Derived
和MoreDerived
时,总是将Base
打印到屏幕上.有没有一种方法可以让Typeid与派生类一起使用?还是除了typeid
之外还有另一种方法?
Problem is, I always get Base
printed to the screen, when I need to see Derived
and MoreDerived
. Is there a way to get typeid to work this way with derived classes? Or is there another approach besides typeid
?
注意:我要向已经编码的套件中添加功能,所以我不想在基类中添加虚拟方法,派生类自己返回该值.另外,不必担心运行时的开销,这将成为调试编译开关的一部分.
Note: I am adding functionality to an already coded suite, so I don't want to have to add a virtual method to the base class where the derived classes return this value themselves. Also, not worried about runtime overhead, this will be part of a debug compile switch.
推荐答案
在构造函数Base()中,该对象仍然是"Base"实例.在Base()构造函数之后,它将成为Derived实例.尝试在构造完成后 ,它将起作用.
In the constructor Base(), the object is still a "Base" instance. It will become a Derived instance after the Base() constructor. Try to do it after the construction and it will work.
例如:
http://www.artima.com/cppsource/nevercall.html
这篇关于以编程方式获取派生类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!