具有多重继承的不明确的基础

Dav*_*ria 24 c++ casting

我试图在一个大型库中编写一些类的子类.我得到一个"模糊的基础"错误.以下是该问题的可编辑示例:

#include <iostream>

// I can't change these because they are in the library:
class InteractorStyle {};
class InteractorStyleCamera : public InteractorStyle {};
class InteractorStyleImage : public InteractorStyle {};

// These are my subclasses (so I can change them):
class PointSelector : public InteractorStyle {};
class PointSelector2D : public InteractorStyleCamera, public PointSelector
{
  // This function has to exist exactly like this (a requirement of the library):
  static PointSelector2D* SafeDownCast(InteractorStyle *o)
  {
    return static_cast<PointSelector2D *>(o);
  } 
};


int main()
{

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误是

错误:'InteractorStyle'是'PointSelector2D'的模糊基础.

在这种情况下我能做些什么吗?

Joh*_*0te 17

你的问题是Interactor样式被继承两次 - 一次是PointSelector2D,一次是InteractorStyleCamera.这意味着您的班级中包含每个成员的2个版本.

查看:

使用多重继承时,如何避免死亡之钻?

并尝试虚拟继承.


AnT*_*AnT 5

您可以通过两步转换来表面上“修复”它。例如

static_cast<PointSelector2D *>(static_cast<InteractorStyleCamera *>(o));
Run Code Online (Sandbox Code Playgroud)

当然,您必须记住,这可以“修复”语法,但不能解决潜在的结构性问题。您的内部PointSelector2D有两个InteractorStyle基础子对象。根据您从哪个InteractorStyle基础子对象开始,上载路径不同。采取正确的道路非常重要。我上面写的是为了InteractorStyle里面的InteractorStyleCamera。对于其他基地,适当的up势将是

static_cast<PointSelector2D *>(static_cast<PointSelector *>(o));
Run Code Online (Sandbox Code Playgroud)

如果仅提供了一个InteractorStyle *指针,而该指针没有指向该指针所指向的基础的额外信息,那么您就无法使用来解决您的问题static_cast。无法知道要采用哪种上行路径。错误的选择将产生完全没有意义的结果。

正如已经指出的那样,dynamic_cast在这种情况下可以提供帮助,但是它还有其他要求(多态起始类型)。您的类型不是多态的(至少在您引用的示例中),因此dynamic_cast不会接受上载。