我会尝试检查一个指针作为参数如下传递什么类型:如何在运行时检查类型?
#include <iostream>
struct A{};
struct B:A{};
struct C:A{};
C *c = new C;
B *b = new B;
A *a = new A;
void foo (A *a)
{
if(dynamic_cast<B*>(a))
{
std::cout << "Type is B*" << std::endl;
//cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct B*' (source type is not polymorphic)
}
if(dynamic_cast<C*>(a))
{
std::cout << "Type is C*" << std::endl;
//cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct C*' (source type is not polymorphic)
}
}
但甚至不进行编译。有可能这样做吗?我的意思是,确定什么指针指向我们作为函数参数传递的类型?
“A”中至少需要一个'virtual'函数,最简单的是声明一个虚拟析构函数。 –
@πάνταῥεῖ用于什么?虚拟函数如何帮助我在运行时确定类型?没有看到...... –
编译器在这种情况下创建了一个vtable,这对'dynamic_cast'是必需的。 –