gpt4 book ai didi

c++ - 我可以使用 decltype() 或其他方法通过指针获取真实类型吗?

转载 作者:行者123 更新时间:2023-12-04 16:57:24 30 4
gpt4 key购买 nike

例如:

class Foo {

};

class Bar : public Foo {

};

int main() {
Foo* foo = new Bar;

std::cout << typeid(decltype(*foo)).name() << std::endl;
}

我尝试了一些语法,有或没有 decltype ,但结果都是关于类型 Foo .我可以通过任何方式获得类型 Bar通过 Foo 类型的指针?

附言我只想在运行时获取类型信息,欢迎任何黑客攻击。

编辑:if/else 和 dynamic_cast如果我有很多类型,技巧不是很可接受。

最佳答案

首先,对象的动态类型只能通过多态类类型获得,这意味着基类必须至少有一个虚函数。

class Foo {
public:
virtual ~Foo() = default;
};

class Bar : public Foo {

};

其次,动态类型是通过应用 typeid获得的运算符直接指向引用对象的表达式:
int main() {
Foo* foo = new Bar;

std::cout << typeid(*foo).name() << std::endl;
}
decltype是仅编译时的运算符。

关于c++ - 我可以使用 decltype() 或其他方法通过指针获取真实类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823067/

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