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/