CLASS_NAME 未声明 - 不能 dynamic_cast(目标不是指针或对完整类型的引用)
CLASS_NAME not declared - cannot dynamic_cast (target is not pointer or reference to complete type)
我有以下代码:
#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
不是指向完整类型的指针?
提前致谢。
稍后再定义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],
The result of the expression dynamic_cast<T>(v)
is the result of
converting the expression v
to type T
. T
shall be a pointer or
reference to a complete class type, or “pointer to cv void.”
我有以下代码:
#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
不是指向完整类型的指针?
提前致谢。
稍后再定义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],
The result of the expression
dynamic_cast<T>(v)
is the result of converting the expressionv
to typeT
.T
shall be a pointer or reference to a complete class type, or “pointer to cv void.”