派生类不能用另一个基类的成员重载基类中的私有成员
derived class cannot overload private member in base class with that from another base class
我正试图使用多重继承来覆盖私有基类成员。基类Base
从它自己的私有基类ClassTypeBase
继承成员class_type_
,这应该使它对从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_; }
};
然而,即使无法从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.
有人能解释一下我缺了什么吗?
谢谢!
在名称查找/解析逻辑中,编译器要做的第一件事就是毫不含糊地解析名称。只有在解析了名称之后,才考虑可访问性。
在您的情况下,Base
对ClassTypeBase
的private
继承在名称明确解析之前不会考虑。这是你理解中遗漏的关键问题。
我假设你知道如何解决歧义,因为你没有问怎么做。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何使用基类指针引用派生类成员
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 如果基类包含双指针成员,则派生类的构造函数
- 继承和友元函数,从基类访问受保护的成员
- 如何基于模板化类的基类专门化成员函数
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 在派生类中使用基类的私有成员变量的最佳方法
- 为什么我需要在成员发起器列表中重复基类的模板参数?
- 继承:调用基类的成员和方法
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 当空基类也是成员变量时,为什么禁止空基优化?
- 引用基类模板的成员变量的简单方法
- 将基类的成员函数重载到其他派生类C++
- C++ 使用派生类方法更改基类数据成员
- 在成员构造函数之后调用基类构造函数
- 派生类看不到基类成员
- 使用派生类中的静态成员而不是基类
- 指向成员的 C++ 指针(指向成员基类的指针)
- 如何在c++中将模板成员函数的实参转发给成员基类指针