将 typeid 的结果分配给变量
Assigning result of typeid to a variable
我正在尝试弄清楚如何在 Microsoft C++ 2015 中使用 typeid
。https://msdn.microsoft.com/en-us/library/fyf39xec.aspx 中的示例按原样工作,但是当我添加一个明显无害的额外行时,编译器报错。
// 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'
如果整个事情都失败了,我不会感到惊讶,但如果最后一行没有失败,我看不出其余的如何工作。我错过了什么?
啊,只是因为auto
试图复制引用的对象,这在这里做不到。如果您改为说 auto&
.
,它会起作用
我正在尝试弄清楚如何在 Microsoft C++ 2015 中使用 typeid
。https://msdn.microsoft.com/en-us/library/fyf39xec.aspx 中的示例按原样工作,但是当我添加一个明显无害的额外行时,编译器报错。
// 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'
如果整个事情都失败了,我不会感到惊讶,但如果最后一行没有失败,我看不出其余的如何工作。我错过了什么?
啊,只是因为auto
试图复制引用的对象,这在这里做不到。如果您改为说 auto&
.