c++ - 派生类不能用另一个基类的私有(private)成员重载基类中的私有(private)成员

标签 c++

我正在尝试使用多重继承来覆盖私有(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.

谁能解释一下我错过了什么?

谢谢!

最佳答案

在名称查找/解析逻辑中,编译器做的第一件事就是明确地解析名称。只有在解析名称后,才会考虑可访问性。

在您的情况下,BaseClassTypeBaseprivate 继承不会被考虑,直到名称被明确解析为止。这是您理解中遗漏的关键问题。

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

关于c++ - 派生类不能用另一个基类的私有(private)成员重载基类中的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666268/

相关文章:

c++ - 在不同类型的模板化类中创建模板化变量

c++ - OpenGL 从 4*float 格式上传像素数据 (C++)

c++ - 如何使用现有的 Qt 5.1.1 安装 Qt 4.8.4

c++ - 当 boost::lock_guard 被移动时

c++ - 包含函数的 C 宏

c++ - 如何在 C++ 中定义自定义浮点格式(类型)?

c++ - std::forward_list 中可以存在循环吗?

c++ - 代码::阻止链接错误

java - c++ - 计算一个类的实例化次数

c++ - const 变量的值在常量表达式中是否可用,取决于变量类型