typeid.name 返回派生类类型之前的数字

typeid.name returns a number before the derived class type

本文关键字:数字 类型 name 返回 派生 typeid      更新时间:2023-10-16

我有这些类:(类问题很抽象,其他的都是派生的(

class Question{
};
class QSingleChoice{
};
class QMultipleChoice{
};
etc.

我有一个存储多种问题类型的vector<Question*>。在GUI中,我需要知道我必须显示什么类型的问题,所以我使用string questionType = typeid(*question).name()但不是"QSingleChoice","QMultipleChoice"等,而是返回"13QSingleChoice","5QText","9QOrdering"等。这些数字是多少?我是否可以假设它们总是相同的,或者当我在不同的计算机上运行程序时,typeid 可能会返回一些像"19QSingleChoice"或完全不同的东西,比如"ASDQSingleChoice"?

std::type_info::name返回的名称是实现定义的,这意味着完全由每个编译器决定如何表示类型名称。换句话说,这不是你可以依赖的东西。它对于调试很有用,并且可以用于程序的同一运行中的一些比较,但我认为它不会用于更多:您必须检查编译器的文档以确定它是否提供了您需要的保证。

如果需要,通常最好自己引入此类功能,也许以virtual const std::string& classId() const;的形式

。它可以像这样实现:

class Question {
public:
virtual const std::string& getClassId() const = 0;
};
class QSingleChoice : public Question {
public:
const std::string& getClassId() const override
{
static const std::string name{"SingleChoice"};
return name;
}
};

class QMultipleChoice : public Question {
public:
const std::string& getClassId() const override
{
static const std::string name{"MultipleChoice"};
return name;
}
};

或者,可以创建并返回枚举而不是字符串名称。

但是,首先确保您首先确实需要它。很多时候,需要检查和识别隐藏在抽象接口后面的特定类型表明设计不好。如果GUI是程序不可或缺的一部分,也许Question可以简单地提供虚拟功能,例如virtual void display() const;。或者,如果 GUI 在很大程度上是问题外部的,也许使用访问者模式可能更合适。