题
我想知道什么区别 typeid
和 typeof
在C++。这是什么我知道:
此外,在这里是代码的测试测试,我已经创建了那里我发现 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
解决方案
C++的语言没有这样的东西 typeof
.你必须看一些编译器的具体扩展。如果你正在谈论的海湾合作委员会 typeof
, 然后一个类似的特征是存在C++11通过关键字 decltype
.再次的,C++已经没有这样 typeof
关键词。
typeid
是用C++语言操作者返回的类型识别信息在运行时间。它基本上返回一个 type_info
对象,这是男女平等与其他 type_info
对象。
请注意,只有定义的财产的返还 type_info
对象是其在平等和不平等--可比性,即 type_info
对象描述不同类型应比较不平等,同时 type_info
对象描述的相同类型要比较相等。其他的一切都是执行定义。方法返回的各种"名称"不能保证返回任何东西可读的,甚至不保证返回任何东西。
还注意到,上述可能意味着(尽管该标准似乎并没有提到它明确),连续的应用 typeid
相同类型可能返回的不同 type_info
对象(其中当然,仍然要比较相等)。
其他提示
之间的主要差别是在两个以下
- 类型是一个汇编的时间构造和返回式定义的,在编制时间
- typeid是运行建造,因此提供信息有关的类型的运行时的价值。
类型的参考: http://www.delorie.com/gnu/docs/gcc/gcc_36.html
typeid参考: https://en.wikipedia.org/wiki/Typeid
typeid
可以操作在运行时,与回对象的描述,运行时间类型的对象,这必须是指向一个目的一类与虚拟方法,以便为 RTTI(运行的时间类型的信息) 被保存在类。它还可以得到编纂的时间类型的一种表达或一种类型的名字,如果不给予的指针一类的运行时间类型的信息。
typeof
是GNU扩展,给你的类型的任何表达在编译时间。这可能是有用的,例如,在宣布暂时的变量在宏可能被用于多种类型。C++,你通常会使用 模板 代替。
回答其他问题:
我的下列试验码不typeid 不出正确的类型的名称。怎么了?
有没有什么是错误的。你看到什么是串表示的种类型的名称。标准C++不力编译器,来这些的确切名称之类的,只是达到的实施者(的编译器供应商)来决定什么是合适的。在短短的名称是最编译器。
这是两个不同的工具。 typeof
返回的种类型的表达,但它不是标准。C++0x也有一些是被称为 decltype
这并同样的工作,据我所知.
decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];
而 typeid
用于与多晶型类型。例如,可以说, cat
派 animal
:
animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
// the object is of type cat! but the pointer is base pointer.
}
typeid提供的数据的类型在运行时,当时提出的要求。Typedef是一个汇编的时间建造,定义了一种新的类型说明之后。没有类型的用C++ 出现为(如发言者的意见):
std::cout << typeid(t).name() << std::endl; // i
std::cout << typeid(person).name() << std::endl; // 6Person
std::cout << typeid(employee).name() << std::endl; // 8Employee
std::cout << typeid(ptr).name() << std::endl; // P6Person
std::cout << typeid(*ptr).name() << std::endl; //8Employee
你可以用提高demangle完成一个漂亮的名称:
#include <boost/units/detail/utility.hpp>
和一些像
To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);