c++ - 不完整的类 : Convert void* to pointer to class type via dynamic_cast

标签 c++ casting forward-declaration dynamic-cast incomplete-type

我有 2 个类 A 和 B。B 派生自 A。A 有一个函数指针成员,其参数是 B 的对象。这些类定义如下:

class B;
typedef double (*func_ptr)(B *);

class A
{
  private:
    func_ptr func;
};

class B: public A
{
  private:
    double C;
};

当我尝试将 void* 动态转换为 A* 或 B* 时,出现以下错误:

void *v_ptr;
A *a_ptr = dynamic_cast<A*>(v_ptr);
B *b_ptr = dynamic_cast<B*>(v_ptr);

error: the operand of a pointer dynamic_cast must be a pointer to a complete class type

我不知道为什么会发生这种情况。这两个类中都没有虚拟方法。我知道类的前向声明不能用于声明成员,但这里它用于定义指针。

谁能解释一下为什么我会收到此错误?

最佳答案

您无法通过 dynamic_cast 转换 void*dynamic_cast 要求的表达式必须引用完整的类类型,而 void 则不然。

(强调我的)

lvalue of a complete class type if new_type is a reference, prvalue of a pointer to complete class type if new_type is a pointer.

顺便说一句:转换类型也应该引用完整的类类型。

pointer to complete class type, reference to complete class type, or pointer to (optionally cv-qualified) void

关于c++ - 不完整的类 : Convert void* to pointer to class type via dynamic_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765952/

相关文章:

c++ - opencv=3.1.0 的背景减法器

c++ - 使用 Qt Creator 表单进行适当的子类化?

c - 我是否转换 malloc 的结果?

c++ - 如何在将内部类作为参数的命名空间中声明友元函数?

forward-declaration - 前向声明和前向引用有什么区别?

c++ - 使用递归算法求解背包

c++ - 如何阅读模板偏特化?

swift - 将 UnsafeMutablePointer 转换为 [String :AnyObject]

c - 一种在 C 中自动将字符串文字转换为 `unsigned char*` 的方法?

bash - 在 Bash 或 Shell 脚本中转发函数声明?