C++ compiler error involving private inheritance

孤街醉人 提交于 2020-01-03 10:56:11

问题


Could someone please explain the following compiler error to me:

struct B
{
};

template <typename T>
struct A : private T
{
};

struct C : public A<B>            
{                                                                             
    C(A<B>);   // ERROR HERE
};

The error at the indicated line is:

test.cpp:2:1: error: 'struct B B::B' is inaccessible
test.cpp:12:7: error: within this context

What exactly is inaccessible, and why?


回答1:


Try A< ::B> or A<struct B>.

Inside of C, unqualified references to B will pick up the so-called injected-class-name, it is brought in through the base class A. Since A inherits privately from B, the injected-class-name follows suit and will also be private, hence be inaccessible to C.

Another day, another language quirk...




回答2:


The problem is name shielding of struct B . Check it out:

struct B{};

struct X{};

template <class T>
struct A : private T
{};

struct C : public A<B>
{
    C(){
          A<X> t1;     // WORKS
 //       A<B> t2;     // WRONG
          A< ::B> t3;  // WORKS
    }   
};

int main () {
}



回答3:


You are making A privately inherit from B when you do A<B>, and that means that B::B is private so you can't construct a C.



来源:https://stackoverflow.com/questions/9223153/c-compiler-error-involving-private-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!