涉及私有继承的C++编译器错误

C++ compiler error involving private inheritance

本文关键字:C++ 编译器 错误 继承      更新时间:2023-10-16

有人能向我解释以下编译器错误吗:

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

指示行的错误为:

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

什么是无法访问的,为什么?

尝试A< ::B>A<struct B>

C内部,对B的非限定引用将获得所谓的注入类名,它是通过基类A引入的。由于AB私有继承,注入的类名也将是私有的,因此C无法访问。

又是一天,又是一种语言怪癖。。。

问题是结构体B的名称屏蔽。看看:

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 () {
}

在执行A<B>时,您正在使A privateB继承,这意味着B::Bprivate,因此无法构造C