c++ - 解决 C++ 中不明确的 this 指针

标签 c++ multiple-inheritance virtual-inheritance

我正在尝试从旧类派生新类。基类声明如下所示:

class Driver : public Plugin, public CmdObject
{
protected:
    Driver();

public:
    static Driver* GetInstance();
    virtual Engine& GetEngine();
public:
    // Plugin methods...
    virtual bool InitPlugin (Mgr* pMgr);
    virtual bool Open();
    virtual bool Close();

    // CmdObject
    virtual bool ExecObjCmd(uint16 cmdID, uint16 nbParams, CommandParam *pParams, CmdChannelError& error);

    Mgr *m_pMgr;

protected:
    Services *m_pServices;
    Engine m_Engine;
};

它的构造函数如下所示:

Driver::Driver() : 
    YCmdObject("Driver", (CmdObjectType)100, true),
    m_Engine("MyEngine")
{
    Services *m_pServices = NULL;
    Mgr *m_pMgr = NULL;
}

所以当我创建派生类时,我首先尝试简单地从基类继承:

class NewDriver : public Driver

并复制构造函数:

NewDriver::NewDriver() : 
    CmdObject("NewDriver", (EYCmdObjectType)100, true),
    m_Engine("MyNewEngine")
{
    Services *m_pServices = NULL;
    Mgr *m_pMgr = NULL;
}

编译器(Analog Devices 的 VisualDSP++ 5.0)不喜欢这样:

".\NewDriver.cpp", line 10: cc0293:  error: indirect nonvirtual base
      class is not allowed
 CmdObject("NewDriver", (EYCmdObjectType)100, true),

有道理,所以我决定直接继承Plugin和CmdObject。为了避免多重继承歧义问题(我是这么想的),我使用了虚拟继承:

class NewDriver : public Driver, public virtual Plugin, public virtual CmdObject

但是,在 NewDriver 中的虚拟方法的实现中,我尝试调用采用 Plugin* 的 Mgr::RegisterPlugin 方法,我得到了这个:

".\NewDriver.cpp", line 89: cc0286:  error: base class "Plugin" is
      ambiguous
 if (!m_pMgr->RegisterPlugin(this))

this 指针是如何产生歧义的,我该如何解决?

谢谢,

--保罗

最佳答案

如果您从 Driver 派生,则不必显式调用 Driver 基类的构造函数:

class NewDriver : public Driver { /* ... */ };
NewDriver::NewDriver() : Driver() {}

Driver 的构造函数然后初始化它自己的基,你不必也不应该直接这样做。
如果它应该有不同的行为,让它接受参数:

class Driver : /* ... */ {
public:
    Driver(const std::string& name /* , ... */)
      : CmdObject(name /* , ... */)
    {}
    // ...
};

NewDriver::NewDriver() : Driver("NewDriver" /* , ... */) {}

关于c++ - 解决 C++ 中不明确的 this 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2807293/

相关文章:

c++ - 使用多重继承时的编译错误

c++ - 多继承C++的菱形继承(钻石问题)

c++ - 以编程方式改变图像

C++ 左值和右值

c++ - 多重继承 : calling all the overriden functions

c++ - 构造虚拟基类时的编译器行为

c++ - 指向基于虚拟接口(interface)的可变参数模板类的指针

c++ - 如何更改QGraphicsRectItem的颜色

c++ - 计算 VS2015 C++ 项目的代码指标

c++ - 了解虚拟派生类的大小