c++ - 在派生类接口(interface)中隐藏基类的特定功能

标签 c++ using virtual-inheritance

struct IA 
{
    virtual void Init() = 0;
    .....
};

struct A : public IA
{
    void Init() {};
    .....
};

struct B : public A
{
    int Init() { return 1; };
};

通过这样的设计,我得到了error C2555: 'B::Init': overriding virtual function return type ...

我能以某种方式对 A 隐藏 Init() 吗,我不想隐藏其他 A 的功能。 A类不仅通过B类从其他地方作为A类使用。

编辑:我需要在层次结构中有两个 Init 函数,只是返回类型不同。 我不需要在 B 类型的对象上调用 A::Init。 其实我可以通过

struct B : private A
{
    using A::.... // all, except Init
    int Init() { return 1; };
};

但是A里面有很多函数:(

最佳答案

由于继承,您的 struct B 包含函数签名 void Init();int Init(); 并且 C++ 不允许重载仅在返回类型上不同的方法。

可能的不雅解决方案:

  • 您可以通过将 struct A 中的 void Init(); 方法声明为私有(private)并保留您希望继承的其余方法来修复此错误公开。
  • 另一个修复方法是添加一个虚拟参数,例如 bool 并使用 Init(true) 调用该方法。请注意,您不能为此虚拟参数定义默认值,否则您最终会遇到同样的错误。

关于c++ - 在派生类接口(interface)中隐藏基类的特定功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22022392/

相关文章:

c++ - 运算速度

php - 我想在mysql中使用php实现行级锁定

c# "using"语句后跟 try 语句 在这种情况下可以省略括号吗?

c++ - 在多级继承的情况下无法理解虚拟基类构造函数

c++ - 虚拟继承和委托(delegate)实现

c++ - 什么时候虚拟继承是一个好的设计?

c++ - 打印小于 100 的质数

c++ - 当对象的指针存储在 vector 中时,如何访问对象中的方法?

c# - 什么相当于 C# 中的 Windows API CreateEvent 函数

c++ - 为什么 `using`关键字不能用于静态类成员?