【问题标题】:How to check which derived class your object is with typeid?如何使用 typeid 检查您的对象是哪个派生类?
【发布时间】:2013-05-28 04:03:26
【问题描述】:

所以我想测试我的对象是药水还是武器。我如何使用 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--;
}
}

【问题讨论】:

  • 你看过factory pattern吗?
  • 哈!我希望我有。我明年学习软件设计模式,但我会尝试理解这篇文章。 :(
  • dynamic_cast 是一种方式。
  • 对象的名称在哪里
  • 另外,由于您使用的是模板,您可能希望将“创建新对象的函数”设为模板参数或函数参数,以便函数本身不会开始做出假设关于对象。对于 11 之前的 C++,您需要一个仿函数对象;对于 C++11,您需要使用 std::function

标签: c++ polymorphism typeid


【解决方案1】:

我不建议使用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 语言但易于理解)。

【讨论】:

    【解决方案2】:

    我认为 typeid 就足够了,这个网站解释了它是如何工作的http://www.cplusplus.com/reference/typeinfo/type_info/?kw=type_info

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2013-11-23
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多