【发布时间】:2015-03-06 08:25:08
【问题描述】:
我有以下代码:
#include <iostream>
using namespace std;
class A{
};
class B: public A{
public:
void f(A *ptr){
if(dynamic_cast<C *>(ptr)!=0){ // errors in this line
cout<<"ptr is pointing to C object\n";
}
}
};
class C: public B{
};
int main(){
A *aptr = new C();
B *bptr = new B();
bptr->f(aptr);
return 0;
}
当我尝试编译时,我得到了错误:
'C' has not been declared.
所以我在class B的代码上方添加了一个前向声明class C;,然后尝试再次编译它,但它给出了错误:
cannot dynamic_cast 'ptr' (of type 'class A*') to type 'struct C*' (target is not pointer or reference to complete type)
1) 为什么在第一个错误中,class B 在同一个 .cpp 文件中时看不到其派生的 class C?
2) 为什么在第二个错误编译器中说class C 不是指向完整类型的指针?
提前致谢。
【问题讨论】:
标签: c++ dynamic-cast