以编程方式获取派生类的名称 [英] Programatically getting the name of a derived class

查看:148
本文介绍了以编程方式获取派生类的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试做类似以下的事情:

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;



到我的屏幕,当我需要看到派生 MoreDerived 。有没有办法得到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()构造函数之后的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屋!

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