如何在C++中检查对象的类?
How can I check an object's class in C++?
假设我有一个基类的对象向量,但用它来包含许多派生类。我想检查该向量的成员是否属于特定类。我该怎么做?我可以考虑制作一个派生类的模板,该模板接受基类的参数,但我不确定如何将类与对象进行比较。
如果你的基类有一些虚拟成员(即它是多态的,因为我认为它应该在这种情况下),你可以尝试向下投射每个成员以找出它的类型(即使用 dynamic_cast
)。
否则,您可以使用RTTI(即 typeid
)。
您可以使用dynamic_cast
但是如果你需要这样做,那么你可能有一个设计问题。 你应该使用多态性或模板来解决这个问题。
看看这个例子:
#include <iostream>
using namespace std;
#include <typeinfo>
class A
{
public:
virtual ~A()
{
}
};
class B : public A
{
public:
virtual ~B()
{
}
};
void main()
{
A *a = new A();
B *b = new B();
if (typeid(a) == typeid(b))
{
cout << "a type equals to b typen";
}
else
{
cout << "a type is not equals to b typen";
}
if (dynamic_cast<A *>(b) != NULL)
{
cout << "b is instance of An";
}
else
{
cout << "b is not instance of An";
}
if (dynamic_cast<B *>(a) != NULL)
{
cout << "a is instance of Bn";
}
else
{
cout << "a is not instance of Bn";
}
a = new B();
if (typeid(a) == typeid(b))
{
cout << "a type equals to b typen";
}
else
{
cout << "a type is not equals to b typen";
}
if (dynamic_cast<B *>(a) != NULL)
{
cout << "a is instance of Bn";
}
else
{
cout << "a is not instance of Bn";
}
}
相关文章:
- 检查哪个对象调用了另一个对象的对象方法
- 如何实现自定义匹配器以检查 Catch2 中的对象相等性
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 使用 gtest 框架在单元测试代码中检查目标对象的私有变量的最佳实践是什么?
- OpenglGL - 如何检查光标是否与对象区域重合?
- 微机器人 - 检查点是否在对象内部
- 如何在共享指针向量中检查重复的"ofstream"对象
- 检查哪个子类是父类对象
- 如何检查对象有效
- 如何检查指针后面的对象是否有效或已删除?
- 什么更有效率?在重载函数中或通过在基类函数中检查对象类型来实现
- Visual Studio 2017 无法检查静态链接库中对象中的 STL 容器
- 如何检查C++矢量中的哪些对象
- 检查成员函数是否返回临时对象或数组对象
- 类返回对象类型,但如何返回和检查 null
- 执行输入检查并在C++中初始化对象
- Python C API:如何检查对象是否是类型的实例
- 在一个作用域中推送五个对象指针,然后检查对象的布尔值是否为 false,会给出错误
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真