从子类访问私有继承类的名称

时间:2017-01-11 15:52:16

标签: c++ inheritance

以下代码无法使用g ++编译此错误,并且与clang类似的错误。

main.cpp:16:19: error: 'QByteArray' is a private member of 'QByteArray'
        Container2(const QByteArray &ba);
                         ^
main.cpp:3:18: note: constrained by private inheritance here
class Container1:private QByteArray
                 ^~~~~~~~~~~~~~~~~~
../edge-clang/qt5/include/QtCore/qbytearray.h:167:21: note: member is declared here
class Q_CORE_EXPORT QByteArray
                    ^
main.cpp:18:30: error: 'QByteArray' is a private member of 'QByteArray'
Container2::Container2(const QByteArray &ba):Container1(ba){}
                             ^
main.cpp:3:18: note: constrained by private inheritance here
class Container1:private QByteArray
                 ^~~~~~~~~~~~~~~~~~
../edge-clang/qt5/include/QtCore/qbytearray.h:167:21: note: member is declared here
class Q_CORE_EXPORT QByteArray
                    ^

我不明白为什么Container2不允许继承Container1并通过公共构造函数初始化它,即使QByteArray的继承是私有的。

#include <QByteArray>

class Container1:private QByteArray
{
public: 
    Container1() {}
    Container1(const QByteArray &ba);
};

Container1::Container1(const QByteArray &ba):QByteArray(ba){}

class Container2:public Container1
{
public:
    Container2() {}
    Container2(const QByteArray &ba);
};
Container2::Container2(const QByteArray &ba):Container1(ba){}

int main(int argc,char *argv[])
{
    QByteArray ba;
    Container1 c1(ba);
    Container2 c2(ba);
}

1 个答案:

答案 0 :(得分:36)

这是一个很棒的错误!

C,&#34; A&#34;意味着&#34;我从我的基地获得的注入类名 A&#34;。
您可以将其视为C::B::A 当然,由于私有继承,该基础是无法访问的:

class A {};

class B : private A {
public:
   B() {}
   B(const A&) {}  
};

class C : public B {
public:
   C(const A&) {}
};

int main()
{
   A a;
   B b(a);
   C c(a);
}

// main.cpp:11:13: error: 'class A A::A' is inaccessible within this context
//      C(const A&) {}
//              ^
// main.cpp:1:9: note: declared here
//  class A {};
//        ^

live demo

您可以通过调用::A来解决此问题,采用更间接的路径来实际命名完全相同的类型:

class A {};

class B : private A {
public:
   B() {}
   B(const A&) {}  
};

class C : public B {
public:
   C(const ::A&) {}
};

int main()
{
   A a;
   B b(a);
   C c(a);
}

// OK

live demo

顺便说一句,完全相同的逻辑适用于private继承的成员变量:

int x = 1;

class A
{
private:
   int x = 2;
};

class B : A {
public:
   B() { int y = x; }
};

int main()
{
   A a;
   B b(a);
}

// main.cpp: In constructor 'B::B()':
// main.cpp:11:17: error: 'int A::x' is private within this context
//    B() { int y = x; }

live demo

从表面上看,这一切看起来都很愚蠢,但这可能是一个很好的理由。

在你的情况下,然后:

Container2(const ::QByteArray &ba);