【问题标题】:Multiple inheritence with default implementation not working - forced to always override default implementation默认实现的多重继承不起作用 - 强制始终覆盖默认实现
【发布时间】:2018-04-27 07:19:49
【问题描述】:

我想做的事

  • 我想要一个基础接口和很多扩展这个基础接口的子接口
  • 我想要默认接口​​的默认实现
  • 我希望我的所有子接口实现都扩展默认实现,并且只覆盖他们想要的那些方法

我已经定义了以下公共接口 - 我为其开发插件的 SDK 需要这些接口

// the base interface
class DYNAMIC_ATTRIBUTE IMasterProfile : public IVWUnknown
{
    public:

        virtual Uint16      VCOM_CALLTYPE GetNodeVersion() = 0;
        // ...

}

// one of many sub interfaces extending the default one
class DYNAMIC_ATTRIBUTE ISomeProfile : public IMasterProfile
{
    public:

        virtual void        VCOM_CALLTYPE SwapData() = 0;
};

我的实现如下所示:

class DYNAMIC_ATTRIBUTE MasterProfile : public virtual IMasterProfile
{
    public:
        Uint16 VCOM_CALLTYPE GetNodeVersion() override { return 0; };
        // ...
}

class DYNAMIC_ATTRIBUTE SomeProfile : public MasterProfile, public virtual ISomeProfile
{
    public:
        void VCOM_CALLTYPE SwapData() override { }
}

问题:

编译器抱怨SomeProfile 是抽象的并且没有实现GetNodeVersion 函数。我该如何解决这个问题? SomeProfile 正在扩展 MasterProfile 并且这个类正在实现 GetNodeVersion 函数...

编辑:可能的解决方案

我可以将IMasterProfile 默认实现移动到标题中,一切正常(另外我删除了虚拟继承)。我很好奇这是否可以在不将默认实现移动到标题中的情况下解决...

【问题讨论】:

  • 如果您的ISomeProfile 使用public virtual IMasterProfile,这个问题不会消失吗?
  • 我也这么认为。但是 SDK 不允许我这样做。然后它抱怨它无法将IVWUnknown* 转换为ISomeProfile*,因为隐式转换了虚拟基类...

标签: c++ inheritance multiple-inheritance


【解决方案1】:

问题在于模棱两可。您必须在ISomeProfile 中实现GetNodeVersion。否则 SomeProfile::ISomeProfile::GetNodeVersion 没有定义,它是抽象的。 考虑这段代码:

class IMasterProfile
{
public:
    virtual int GetNodeVersion() = 0;
};

class ISomeProfile : public IMasterProfile
{
public:
    virtual void SwapData() = 0;
    int GetNodeVersion() override { return 2; };
};

class MasterProfile : virtual IMasterProfile
{
public:
 int GetNodeVersion() override { return 3; };
// ...
};

class SomeProfile : public MasterProfile, public virtual ISomeProfile
{
public:
    SomeProfile(){ std::cout<<ISomeProfile::GetNodeVersion();}
    void print()
    {
        std::cout<<GetNodeVersion(); // ERROR: Call to the "GetNodeVersion" is ambiguous
        std::cout<<MasterProfile::GetNodeVersion(); // Call to the GetNodeVersion from MasterProfile
        std::cout<<ISomeProfile::GetNodeVersion(); // Call to the GetNodeVersion from ISomeProfile, without implementing it's virtual method
    }
    void SwapData() override { }
};

所以问题是行,当你想在SomeProfile中使用时:

std::cout<<ISomeProfile::GetNodeVersion(); // Call to the GetNodeVersion from ISomeProfile, without implementing it's virtual method

没有实现就做不到,需要定义。

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多