typeid.name 返回派生类类型之前的数字
typeid.name returns a number before the derived class type
我有这些类:(类问题很抽象,其他的都是派生的(
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 在很大程度上是问题外部的,也许使用访问者模式可能更合适。
- 你能在 c++ 中将不同的数字类型加在一起吗?
- 检测<T>某些非数字类型 T 的 std::numeric::type 的特化
- 为什么数字类型只有"to_string()"?
- 从 std::stringstream 读取uint8_t为数字类型
- 枚举超过了最大数字类型的大小
- 为什么将指针铸成数字类型是不安全的
- 我应该始终将适当的文字用于数字类型
- 如何识别C中字符串中包含的数字类型
- 如何对具有带符号数字类型的事物进行谓词
- 我可以得到一个适用于任何数字类型的模板化均匀分布生成器吗?
- C++隐式数字类型降级
- 依靠任何数字类型(无符号、整数等)的隐式提升来加倍是否安全
- 用于显示不同数字类型的函数重载
- 创建几个相互不兼容的数字类型
- 同类数字类型之间的转换
- 数字类型介于0和1之间
- 将字符串转换为数字类型的通用方法
- 为小循环计数器选择什么数字类型
- 如何将处理不同数字类型的C函数库包装到c++模板类中
- 如何将来自用户定义文字的可变char模板参数转换回数字类型