C++获取对象类型
我有一个 C++ 应用程序,它具有以下类:
class AAA
class BBB
继承自AAA
class CCC
继承自AAA
class DDD
继承自CCC
(所有类都标记为 public
)
现在我有以下地图:
map <DWORD, AAA*>
我在中找到一个 AAA
对象map
,由DWORD id
组成,但现在我想知道AAA
的类型是什么:
这将是逻辑:
if(AAA is BBB)
{
...
}
if(AAA is CCC)
{
...
}
if(AAA is DDD)
{
...
}
你知道吗如何用C++编写它(不添加getType()
多态函数)?
I have a C++ application which has the following classes:
class AAA
class BBB
inherits fromAAA
class CCC
inherits fromAAA
class DDD
inherits fromCCC
(All of the classes are marked as public
)
Now I have the following map:
map <DWORD, AAA*>
I find an AAA
object in the map
, by a DWORD id
, but now I want to know what is the type of AAA
:
this will be the logic:
if(AAA is BBB)
{
...
}
if(AAA is CCC)
{
...
}
if(AAA is DDD)
{
...
}
Do you know how to write it in C++ (without adding a polymorphic function of getType()
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要求这样做表明您的做法是错误的。您正在尝试复制虚拟方法的发明目的。只需在基类中添加一个虚拟方法即可。
在你的调用代码中,你的逻辑很简单:
我意识到你可能不能只是将当前的“dosomething”代码复制/粘贴到其中。但这是您应该在这种情况下使用的模式。也许使用像
GetSomeInfo
这样的东西代替DoSomething
更有意义,调用者可以用它来做任何需要做的事情。此模式的具体用法取决于您的上下文。Requiring this indicates you are doing it the wrong way. You are trying to replicate something that virtual methods were invented for. Just put a virtual method in your base class.
And in your calling code, your logic is simple:
I realize you maybe can't just copy / paste your current "dosomething" code into this. But this is the pattern you should be using for this scenario. Perhaps instead of
DoSomething
it makes more sense to have something likeGetSomeInfo
, that the caller can use to do whatever it needs to do. The specific usage of this pattern depends on your context.如果您的对象是多态的(即至少有一个虚函数),请执行
dynamic_cast
。如果结果不是
NULL
,那么您就有一个T
类型的对象。但在我看来,虚拟功能将是更好的方法。注意:RTTI 需要在编译器上启用(绝大多数情况下都会启用 RTTI)情况)
编辑:感谢@Als和@flipchart的补充
If your object is polymorphic (i.e. has at least one virtual function), do a
dynamic_cast<T*>
.if the result is not
NULL
then you have an object of typeT
. But a virtual function would be a better way to go IMO.Note: RTTI will need to be enabled on your compiler (which it will be in the vast majority of situations)
EDIT: Thanks to @Als and @flipchart for additions