typeid(type).name() 如何决定用户定义的名称 class?我可以改变这种行为吗?

how typeid(type).name() decide name for user define class? and can i change this behaviour?

我想知道用户定义 class typeid(type) 将如何决定用户定义类型的名称 class 检查我下面的学生代码 class 我得到了一个输出像 7Student 但我不明白为什么 7 附加在 Student class.

之前
#include <iostream>

class Person {
    protected:
        std::string name;

    public:
        Person(std::string name)
            : name(name) {}
};

class Student : public Person{
    private:
        std::string id;

    public:
        Student(std::string name,std::string id)
            : id(id) , Person(name) {}
};

template<typename Type>
class Test {
    private:
        Type type;

    public:
        Test(Type type)
            : type(type) {}

        const char* getType() const {
            return typeid(this->type).name();
        }
};

int main() {
    Test<int> *test1 = new Test<int>(5);
    std::cout<<test1->getType()<<std::endl;

    Test<float> *test2 = new Test<float>(1.1);
    std::cout<<test2->getType()<<std::endl;

    Test<double> *test3 = new Test<double>(1.1);
    std::cout<<test3->getType()<<std::endl;

    Test<long> *test4 = new Test<long>(11);
    std::cout<<test4->getType()<<std::endl;

    Test<unsigned int> *test5 = new Test<unsigned int>(11);
    std::cout<<test5->getType()<<std::endl;

    Test<Student> *test6 = new Test<Student>(*(new Student("visrut","111")));
    std::cout<<test6->getType()<<std::endl;      // 7Student

    Test<Person> *test7 = new Test<Person>(*(new Person("visrut")));
    std::cout<<test7->getType()<<std::endl;

    Test<std::string> *test8 = new Test<std::string>("visrut");
    std::cout<<test8->getType()<<std::endl;

    return 0;
}

我尝试了使用扩展 Person class 和不使用扩展 Person class 的代码,但最后一种输出是相同的,它是 7Student

供您参考我的 g++ 编译器输出如下

i
f
d
l
j
7Student
6Person
NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE

现在当我测试 Person class 时它的输出也是 6Person 所以我发现这种行为是 {length of user-define class}{class-name} 但我得到了 [=23= 的奇怪输出] 所以我想问一下我可以在 PersonStudent class 中更改此行为是否有一些内置方法我可以在 PersonStudent 中编写class return 具体 const char * typeid().name() ?

std::type_infoname() 成员完全由实现定义。您无法更改输出的内容,也不知道将输出什么。它甚至可能在运行之间有所不同。

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.

From here.

如果您需要从 class 定义和检索特定名称,您正在考虑做一些称为反射的事情(或者它的一种非常简单的形式)。这不是 c++ 设计的目的,如果可以的话,你应该避免依赖需要这样做。如果您发现确实需要这样做,可以在 How can I add reflection to a C++ application?.

找到更多信息