gpt4 book ai didi

C++ RTTI 和派生类

转载 作者:太空狗 更新时间:2023-10-29 23:48:15 26 4
gpt4 key购买 nike

我的 C++ 有点生疏了。这是我正在尝试做的事情:

class Cmd { };
class CmdA : public Cmd { };
class CmdB : public Cmd { };
...
Cmd *a = new CmdA ();
Cmd *b = new CmdB ();

第一个问题:

cout << typeid (a).name ()
cout << typeid (b).name ()

两者都返回 Cmd * 类型。我想要的结果是 CmdA* 和 CmdB*。任何除了:

if (dynamic_cast <CmdA *> (a)) ...

其次,我想做这样的事情:

class Target {
public:
void handleCommand (Cmd *c) { cout << "generic command..." }
void handleCommand (CmdA *a) { cout << "Cmd A"; }
void handleCommand (CmdB *b) { cout << "Cmd B"; }
};

Target t;
t.handleCommand (a);
t.handleCommand (b);

并获得输出“Cmd A”和“Cmd B”。现在它打印出来“通用命令...”两次。

谢谢

最佳答案

啊但是 typeid(a).name() 将是 Cmd* 因为它被定义为 Cmd*typeid(*a).name() 应该返回 CmdA

http://en.wikipedia.org/wiki/Typeid

此外,传递给 typeid 的任何内容的基类都必须具有虚函数,否则您将返回基类。

MSDN 对此有更 Eloquent 解释:

If the expression points to a base class type, yet the object is actually of a type derived from that base class, a type_info reference for the derived class is the result. The expression must point to a polymorphic type (a class with virtual functions). Otherwise, the result is the type_info for the static class referred to in the expression. Further, the pointer must be dereferenced so that the object it points to is used. Without dereferencing the pointer, the result will be the type_info for the pointer, not what it points to.

关于C++ RTTI 和派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1904606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com