gpt4 book ai didi

C++ 中的 Javas Class 等价物

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:22 25 4
gpt4 key购买 nike

所以我正在学习 C++ 并想编写一个实体组件系统。为此,当我将组件添加到实体时,我需要知道组件的类型。在 Java 中,我只会做这样的事情:

Class<?> someClass = myComponent.class;

我可以在 C++ 中做一些等效的事情吗?我尝试了 typeid(myComponent),但在这种情况下不起作用。

ExtComponent* extended = new ExtComponent();
Component* base = dynamic_cast<Component>(extended);
std::cout << typeid(base).name();

这会返回“class Component”,但我想要在这种情况下返回“class ExtComponent”的东西。我该怎么做。

最佳答案

如果我对您的理解正确,您希望获得对象的动态类型。 (不是变量本身的类型,而是变量(真的)指的是什么)

Typeid 可以工作是因为:

N3337 5.2.8/2:

When typeid is applied to a glvalue expression whose type is a polymorphic class type (10.3), the result refers to a std::type_info object representing the type of the most derived object (1.8) (that is, the dynamic type) to which the glvalue refers[...]

所以,只需添加一些虚函数(或者虚基类),它们就会做你想做的事。

此外,您还必须将 typeid 应用于对象,而不是指针(因为这将返回指针而非对象的 type_info):

Base *b = new Base;
...
typeid(*b); //not typeid(b)

关于C++ 中的 Javas Class<?> 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37567362/

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