我有以下代码:
#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 C;
在的代码上方添加了一个前向声明class B
,然后尝试再次对其进行编译,但随后出现错误:
cannot dynamic_cast 'ptr' (of type 'class A*') to type 'struct C*' (target is not pointer or reference to complete type)
1)为什么在第一个错误中,当它们位于同一.cpp文件中时,class B
看不到其派生内容class C
?
2)为什么在第二个错误编译器中说class C
不是完整类型的指针?
提前致谢。
B::f()
稍后定义。
class B: public A{
public:
void f(A *ptr);
};
class C : public B { /* ... */ };
void B::f(A *ptr) {
if(dynamic_cast<C *>(ptr)!=0){
cout<<"ptr is pointing to C object\n";
}
}
如C ++标准[expr.dynamic.cast]中所述,
表达式
dynamic_cast<T>(v)
的结果是将表达式转换v
为type的结果T
。T
应为完整类类型的指针或引用,或为“ cv void的指针”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句