0
我想弄清楚如何在Microsoft C++ 2015中使用typeid
。https://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'
我會,如果整個事情失敗了少驚訝,但我不明白是怎麼如果最後一行不行,休息可能會奏效。我錯過了什麼?
你不能創建你自己的'std :: type_info'對象。這樣的對象只能作爲'typeid'表達式的值出現。 –
這工作'const std :: type_info&t = typeid(pb);'我想象儘管'auto'應該很聰明,但事實並非如此。 (使用g ++ - 4.9) – bendervader
根據[std :: type_info - cppreference](http://en.cppreference.com/w/cpp/types/type_info)是type_info類既不是CopyConstructible也不是CopyAssignable。 – wimh