如何在运行时检查类型?
How to check a type at runtime?
我试图检查一个指向作为参数传递的类型的指针,如下所示:
#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
的定义。最简单的解决方案:添加虚拟析构函数:
struct A
{
virtual ~A() {}
};
然后:
int main()
{
foo(b);
foo(c);
return 0;
}
输出:
Type is B*
Type is C*
在这里试试:link。
哦,我知道,这只是一个示例代码,但是用 new
创建的这些全局变量看起来很糟糕。
我试图检查一个指向作为参数传递的类型的指针,如下所示:
#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
的定义。最简单的解决方案:添加虚拟析构函数:
struct A
{
virtual ~A() {}
};
然后:
int main()
{
foo(b);
foo(c);
return 0;
}
输出:
Type is B*
Type is C*
在这里试试:link。
哦,我知道,这只是一个示例代码,但是用 new
创建的这些全局变量看起来很糟糕。