派生类不能用另一个基类的成员重载基类中的私有成员

derived class cannot overload private member in base class with that from another base class

本文关键字:成员 基类 重载 另一个 派生 不能      更新时间:2023-10-16

我正试图使用多重继承来覆盖私有基类成员。基类Base从它自己的私有基类ClassTypeBase继承成员class_type_,这应该使它对从Base派生的任何类都完全不可见。

派生类Derived继承自BaseClassType,后者有自己的class_type_定义。这是代码:

class ClassTypeBase {
protected:
static const int class_type_ = 0;
};
class ClassType {
protected:
static const int class_type_ = 1;
};
struct Base : private ClassTypeBase {
virtual int class_type() { return class_type_; }
};
struct Derived : private ClassType, public Base {
int class_type() override { return class_type_; }
};

然而,即使无法从Derived访问ClassTypeBase::class_type_,编译器仍然声称ClassType::class_type_ClassTypeBase::class_type之间存在歧义。

来自Wandbox:

prog.cc:16:44: error: member 'class_type_' found in multiple base classes of different types
int class_type() override { return class_type_; }
^
prog.cc:8:26: note: member found by ambiguous name lookup
static const int class_type_ = 1;
^
prog.cc:3:26: note: member found by ambiguous name lookup
static const int class_type_ = 0;
^
1 error generated.

有人能解释一下我缺了什么吗?

谢谢!

在名称查找/解析逻辑中,编译器要做的第一件事就是毫不含糊地解析名称。只有在解析了名称之后,才考虑可访问性。

在您的情况下,BaseClassTypeBaseprivate继承在名称明确解析之前不会考虑。这是你理解中遗漏的关键问题。

我假设你知道如何解决歧义,因为你没有问怎么做。