【问题标题】:Strange behaviour of the typeid operator?typeid 运算符的奇怪行为?
【发布时间】:2011-01-10 00:00:00
【问题描述】:

使用 XCode 3.2.3(64 位),我得到以下奇怪的输出。我究竟做错了什么?

#include <iostream>
#include <typeinfo>

struct student {

};

int main()  
{  
    int i;
    student obj;

    std::cout << typeid(i).name() << "\n";
    std::cout << typeid(obj).name() << "\n";

    return 0;
}

输出:

i  
7student

【问题讨论】:

标签: c++ xcode typeid


【解决方案1】:

type_info 结构的name() 成员函数是特定于实现的。无法保证它会尝试返回与原始程序中所说的内容相匹配的内容。事实上,C++ ISO 标准(18.5.1.7)实际上说这个函数返回“一个实现定义的 NTBS”(空终止字节字符串)。如果它愿意,它可以让它总是返回字符串“neener neerer I won't tell you the name of this type”。这与 Java 的 Class&lt;?&gt; 类型形成鲜明对比,后者对可以返回和不能返回的内容有非常严格的限制。

如果您想将名称从 std::type_info 转换为更人性化、更易读的名称,请查看 this other question 了解详情。

【讨论】:

    【解决方案2】:

    发生的事情并没有什么特别的。只是 typeid 不承诺返回类型的“原始”名称,而只是 a 名称。

    该函数返回一个实现定义的字符串,如果幸运的话,它是可以识别的,但它不承诺这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2013-10-29
      • 2012-12-01
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多