在C++编程中,typedef和typeid是两个完全不同的概念,分别用于不同的目的。
typedef
typedef 关键字用于为现有的数据类型创建新的名字。这常用于简化复杂的类型声明,或者为特定类型创建更具描述性的别名。typedef 并不创建新的类型,只是为现有的类型定义了一个新的名称。
示例:
typedef unsigned long ulong;
typedef std::vector<int> IntVector;
ulong number = 12345;
IntVector vec = {1, 2, 3, 4, 5};
在这个例子中,ulong 是 unsigned long 的别名,IntVector 是 std::vector<int> 的别名。
typeid
typeid 关键字用于在运行时获取一个对象的类型信息。它返回一个 std::type_info 对象,该对象包含有关类型的信息。typeid 通常与 typeof 关键字一起使用,以便在编译时获取类型信息,但 typeid 是在运行时工作的。
示例:
#include <iostream>
#include <typeinfo>
class Base { };
class Derived : public Base { };
int main() {
Base* basePtr = new Derived();
std::cout << "The type of basePtr is: " << typeid(*basePtr).name() << std::endl;
delete basePtr;
return 0;
}
在这个例子中,typeid(*basePtr).name() 将返回 basePtr 指向的对象的实际类型名,即使 basePtr 的静态类型是 Base*。
总结
typedef用于在编译时创建类型的别名。typeid用于在运行时获取对象的类型信息。
这两个特性分别在不同的上下文中非常有用,但不应混淆它们的用途和工作方式。
489

被折叠的 条评论
为什么被折叠?



