乐闻世界logo
搜索文章和话题

' typeid ' versus ' typeof ' in C++

4 个月前提问
3 个月前修改
浏览次数25

1个答案

1

在C++中,typeidtypeof(或在一些情况下是 decltype)是用于获取类型信息的操作符,但它们在使用和目的上有所不同。

1. typeid

typeid 是C++标准库提供的一个操作符,用于在运行时确定对象的类型或表达式的类型。typeid 与运行时类型识别(RTTI)密切相关。它主要用于多态的情境下,能够提供一个指向 type_info 对象的引用,type_info 对象包含了有关类型的信息。

例子:

cpp
#include <iostream> #include <typeinfo> class Base { public: virtual void print() { std::cout << "Base class" << std::endl; } }; class Derived : public Base { public: void print() override { std::cout << "Derived class" << std::endl; } }; int main() { Base* b = new Derived(); std::cout << "b is: " << typeid(*b).name() << std::endl; // 输出派生类的类型名 delete b; return 0; }

在这个例子中,即使 bBase 类型的指针,typeid 检测到 b 指向 Derived 的实例,并返回 Derived 的类型信息。

2. decltype

decltype 是C++11引入的关键字,用于在编译时推导表达式的类型。它不涉及运行时类型信息,而是完全在编译时解析。

例子:

cpp
#include <iostream> int main() { int x = 5; decltype(x) y = 10; // y的类型被推导为int std::cout << "y is: " << y << std::endl; return 0; }

在这个例子中,decltype(x) 用来推断 x 的类型,并用相同的类型声明变量 y

注意点

  • typeid 需要运行时支持,特别是当涉及到多态类型时。
  • decltype 相对于 typeof(在某些编译器中是一个非标准扩展),它是C++11标准的一部分,因此具有更好的可移植性和标准化。

总结,typeid 主要用于获取运行时类型信息,而 decltype 用于在编译时推断变量或表达式的类型。

2024年6月29日 12:07 回复

你的答案