'bad_cast' in namespace 'std' does not name a type 错误
'bad_cast' in namespace 'std' does not name a type Error
给定下一个代码:
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
class A {
public:
virtual ~A() {
}
};
class B: public A {
public:
};
int main() {
int n = 4;
A a;
A& base = a;
B* ptr = dynamic_cast<B*>(&base);
if (ptr == NULL) {
cerr << "base is not a B";
}
try {
B& derived = dynamic_cast<B&>(base);
derived = *ptr;
} catch (std::bad_cast&) { // ERROR
cerr << "base is not a B";
}
if (n == 3) {
}
return 0;
}
我收到此消息错误,我不明白是什么原因,我该如何解决?
'bad_cast' in namespace 'std' does not name a type
如果您在 http://en.cppreference.com/w/cpp/types/bad_cast 查找文档,它会在顶部告诉您每个 class/function 都需要包含哪些内容。在这种情况下,您需要包括 <typeinfo>
给定下一个代码:
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
class A {
public:
virtual ~A() {
}
};
class B: public A {
public:
};
int main() {
int n = 4;
A a;
A& base = a;
B* ptr = dynamic_cast<B*>(&base);
if (ptr == NULL) {
cerr << "base is not a B";
}
try {
B& derived = dynamic_cast<B&>(base);
derived = *ptr;
} catch (std::bad_cast&) { // ERROR
cerr << "base is not a B";
}
if (n == 3) {
}
return 0;
}
我收到此消息错误,我不明白是什么原因,我该如何解决?
'bad_cast' in namespace 'std' does not name a type
如果您在 http://en.cppreference.com/w/cpp/types/bad_cast 查找文档,它会在顶部告诉您每个 class/function 都需要包含哪些内容。在这种情况下,您需要包括 <typeinfo>