因此,我想测试我的对象是药水还是武器。我该如何使用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块创建对象。下面的示例显示了如何使用这种方法实现加载功能。
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);
}
}
根据您的要求,实现工厂功能或类可能会更有利。 This page描述了工厂模式并提供了示例代码(使用Java,但易于理解)。
关于c++ - 如何使用typeid检查对象是哪个派生类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16783664/