如何使用typeid检查对象是哪个派生类
How to check which derived class your object is with typeid?
所以我想测试我的对象是药水还是武器。我如何用typeid(即或任何事情)做到这一点??
然后我想基于这个条件实例化一个对象。我不能只说T temp,因为那会实例化一个抽象基类(也就是说,我的Item类里面有一个纯虚函数)。
template <typename T>
void List<T>::Load(std::ifstream & file)
{
//Read the number of elements
file.read(reinterpret_cast<char *>(&mNumberOfNodes), sizeof(int));
//Insert nodes into list
//If object is a potion
//T * temp = new Potion;
//If object is a weapon
//T * temp = new Weapon;
for( int i = 0; i < mNumberOfNodes; i++ )
{
temp->Load(file);
this->PushFront(&temp);
mNumberOfNodes--;
mNumberOfNodes--;
}
}
我不建议按照您计划使用的方式使用typeid
来识别对象类型。原因是存储在类型信息中的值可以在不同的构建之间更改。如果发生这种情况,在更改程序之前创建的每个数据文件都将不再工作。
相反,您应该自己定义一组值,并将它们与程序中的各种对象类型关联起来。最简单的方法是在加载文件时使用枚举和switch/case块来创建对象。下面的例子展示了如何使用这种方法实现load函数。
enum ObjectType
{
Potion,
Sword,
Condom
};
template <typename T>
void List<T>::Load(std::ifstream & file)
{
//Read the number of elements
file.read(reinterpret_cast<char *>(&mNumberOfNodes), sizeof(int));
//Insert nodes into list
for( int i = 0; i < mNumberOfNodes; i++ )
{
T* obj = NULL;
int nodeType;
file.read(reinterpret_cast<char *>(&nodeType), sizeof(nodeType));
switch(nodeType)
{
case Potion:
obj = new Potion(file);
break;
case Sword:
obj = new Sword(file);
break;
case Condom:
obj = new Trojan(file);
break;
default:
throw std::runtime_error("Invalid object type");
}
PushFront(&obj);
}
}
根据您的需求实现工厂函数或类可能更有益。本页描述了工厂模式并提供了示例代码(用Java编写,但很容易理解)。
我认为typeid足以做到这一点,这个网站解释了它是如何工作的http://www.cplusplus.com/reference/typeinfo/type_info/?kw=type_info
相关文章:
- 为什么此派生对象无法访问基类的后递减方法?
- 如何在新的派生对象中获取基本对象的数据?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 在没有默认构造函数的情况下创建的派生对象
- OOP 标识派生对象
- 如何创建派生对象的向量?
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 如何从 Gtk::窗口调用派生对象的析构函数
- 无法在派生对象上运行虚拟函数
- 尝试删除指向派生对象的基指针时断言错误
- 存储在一个通用容器中的派生对象.如何避免铸造
- 将派生对象分配给函数内的基类指针
- 替换派生对象向量中的对象"no matching function to call"
- 派生对象调用的 Base 方法的模板推导
- 用于填充 Base 和派生对象的 shared_ptr 向量的函数模板
- C++ UBSAN 对派生对象产生误报
- 如何验证我是否正在使用C++中的基对象或派生对象
- C++ 构造函数和派生对象
- 将派生对象传递给模板
- 指向派生作品的基本指针,即使派生对象不存在