c++ - 嵌套类继承错误

标签 c++ inheritance visual-studio-2013

class A {};
class B : private A {};
class C : private B
{
public:
    class D : private A {}; // Error here
};

此代码给出以下错误(在 VS 2013 中):

nested.cpp(8) : error C2247: 'A' not accessible because 'B' uses 'private' to inherit from 'A'

如果我像这样更改 D 的定义,它会得到修复:

class D : private ::A {};

这是正确的行为吗?如果是,为什么?

一开始我以为是因为 C 私自继承自 B 会隐藏基类。但是,如果我消除“中间人”类 B 并使用它:

class A {};
class C : private A
{
public:
    class D : private A {};
};

错误消失了。

最佳答案

引自 cppreference :

A name that is private according to unqualified name lookup, may be accessible through qualified name lookup

考虑到这一点,让我们看看第一个示例的非限定名称查找如何工作:

class A {};

class B : private A {};

class C : private B
{
public:
    class D : private A {}; // Error here
};
  1. AC 范围内查找。如果在那里定义,就不会有问题。
  2. 它发现 A 是由它的基(私有(private))类 B 私有(private)继承的,因此会引发编译器错误。 Clang 说:
    note: constrained by private inheritance here:
    class B : private A {}; 

Again, as per the quote it should work, if you use fully qualified name, like you have shown

class D : private ::A {};

至于你的最后一个例子:

class A {};

class C : private A
{
public:
    class D : private A {};
};

之所以有效,是因为名称查找适用于属于同一类的所有名称。再次引用 cppreference:

All members of a class (bodies of member functions, initializers of member objects, and the entire nested class definitions) have access to all the names to which a class can access.

关于c++ - 嵌套类继承错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41055052/

相关文章:

c++ - 为什么 clang 缺少参数包错误的默认参数?

c++ - 模板 :Name resolution:Dependent types: -->can any one tell some more examples for this statement?

C++ 运算符重载和继承

c++ - "Signals"来自使用 Visual Studio 的库

c++ - 我想检查一个类实例是否已经存储在 std::vector 中

c++ - 通用设计混合了奇怪的重复模板模式。 C++

python - PyQt4 中的多窗口

python - 向 Python 子类添加描述符

c++ - 将字符串转换为数组,strcpy 不起作用

internet-explorer-8 - VS2013RC需要IE10,但我需要(不需要)IE8