我正在尝试使用多重继承来覆盖私有(private)基类成员。基类,Base
, 继承成员 class_type_
来自自己的私有(private)基地ClassTypeBase
,这应该使它对从 Base
派生的任何类完全不可见.
派生类,Derived
, 继承自 Base
,以及来自 ClassType
, 它有自己的 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_; }
};
然而,即使ClassTypeBase::class_type_
无法从 Derived
访问,编译器仍然声称 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.
谁能解释一下我错过了什么?
谢谢!
最佳答案
在名称查找/解析逻辑中,编译器做的第一件事就是明确地解析名称。只有在解析名称后,才会考虑可访问性。
在您的情况下,Base
对 ClassTypeBase
的 private
继承不会被考虑,直到名称被明确解析为止。这是您理解中遗漏的关键问题。
我假设你知道如何解决歧义,因为你没有问如何去做。
关于c++ - 派生类不能用另一个基类的私有(private)成员重载基类中的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666268/