【发布时间】:2010-12-31 11:32:20
【问题描述】:
我想知道 C++ 中 typeid 和 typeof 之间有什么区别。以下是我所知道的:
另外,这是我创建的测试代码测试,我发现typeid 没有返回我预期的结果。为什么?
main.cpp
#include <iostream>
#include <typeinfo> //for 'typeid' to work
class Person {
public:
// ... Person members ...
virtual ~Person() {}
};
class Employee : public Person {
// ... Employee members ...
};
int main () {
Person person;
Employee employee;
Person *ptr = &employee;
int t = 3;
std::cout << typeid(t).name() << std::endl;
std::cout << typeid(person).name() << std::endl; // Person (statically known at compile-time)
std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time)
std::cout << typeid(ptr).name() << std::endl; // Person * (statically known at compile-time)
std::cout << typeid(*ptr).name() << std::endl; // Employee (looked up dynamically at run-time
// because it is the dereference of a pointer
// to a polymorphic class)
}
输出:
bash-3.2$ g++ -Wall main.cpp -o main
bash-3.2$ ./main
i
6Person
8Employee
P6Person
8Employee
【问题讨论】:
-
您认为您的代码以何种方式无法打印正确的类型名称?对我来说看起来不错。
name()返回的实际字符串是实现定义的。它不必是有效的 C++ 标识符名称,只要是唯一标识类型的 something 即可。看起来您的实现使用了编译器的通用名称修饰方案。 -
谢谢罗伯!我期望那些与我在 en.wikipedia.org/wiki/Typeid 中看到的类型名称完全相同。名称修改在这里可以做什么?
-
如果你像我一样是 typeid 新手:你需要在基类型中有一个虚函数来开启 vtable 否则最后一行会打印基类型。