2015-09-05 95 views
0

我想弄清楚如何在Microsoft C++ 2015中使用typeidhttps://msdn.microsoft.com/en-us/library/fyf39xec.aspx的示例按原样运行,但是当我添加一个显然无害的额外行时,编译器会给出一个错误。将typeid的结果分配给一个变量

// compile with: /GR /EHsc 
#include <iostream> 
#include <typeinfo.h> 

class Base { 
public: 
    virtual void vvfunc() {} 
}; 

class Derived : public Base {}; 

using namespace std; 
int main() { 
    Derived* pd = new Derived; 
    Base* pb = pd; 
    cout << typeid(pb).name() << endl; //prints "class Base *" 
    cout << typeid(*pb).name() << endl; //prints "class Derived" 
    cout << typeid(pd).name() << endl; //prints "class Derived *" 
    cout << typeid(*pd).name() << endl; //prints "class Derived" 
    auto t = typeid(pb); 
} 

最后一行,auto t = typeid(pb);,为我增加了一个,错误是

a.cpp(20): error C2248: 'type_info::type_info': cannot access private member declared in class 'type_info' 
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE\vcruntime_typeinfo.h(104): note: see declaration of 'type_info::type_info' 
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE\vcruntime_typeinfo.h(63): note: see declaration of 'type_info' 

我会,如果整个事情失败了少惊讶,但我不明白是怎么如果最后一行不行,休息可能会奏效。我错过了什么?

+2

你不能创建你自己的'std :: type_info'对象。这样的对象只能作为'typeid'表达式的值出现。 –

+1

这工作'const std :: type_info&t = typeid(pb);'我想象尽管'auto'应该很聪明,但事实并非如此。 (使用g ++ - 4.9) – bendervader

+1

根据[std :: type_info - cppreference](http://en.cppreference.com/w/cpp/types/type_info)是type_info类既不是CopyConstructible也不是CopyAssignable。 – wimh

回答

0

啊,这只是因为auto试图复制引用的对象,这不能在这里完成。如果您改为auto&,它会起作用。

相关问题