C ++ typeid
とtypeof
C ++の違いは何ですか。これが私が知っていることです:
typeid
ドキュメントに記載されている TYPE_INFO C ++ヘッダファイルに定義されているのTypeInfo。typeof
CのGCC拡張およびC ++ Boostライブラリで定義されています。
また、ここに、私が作成したテストコードテストがあります。ここでは、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 ++の識別子名だけである必要はありません何かユニークタイプを識別します。実装がコンパイラの一般的な名前のマングリング方式を使用しているようです。