【问题标题】:CLASS_NAME not declared - cannot dynamic_cast (target is not pointer or reference to complete type)CLASS_NAME 未声明 - 不能 dynamic_cast(目标不是完整类型的指针或引用)
【发布时间】: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


    【解决方案1】:

    稍后定义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&lt;T&gt;(v) 的结果是 将表达式v 转换为类型TT 应为指针或 对完整类类型的引用,或“指向 cv void 的指针。”

    【讨论】:

    • 谢谢您,您的建议奏效了!我必须做的唯一补充是通过创建一个虚拟解构器来制作class A polymporhpic,以便根据您的建议编译代码。
    猜你喜欢
    • 2012-10-19
    • 2016-03-15
    • 2018-05-25
    • 2013-03-11
    • 1970-01-01
    相关资源
    最近更新 更多