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

发布于 2025-01-04 01:28:25 字数 439 浏览 3 评论 0原文

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

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

究竟是什么无法访问,为什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

总攻大人 2025-01-11 01:28:26

问题是 struct 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 () {
}

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 () {
}
月下客 2025-01-11 01:28:26

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

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.

拔了角的鹿 2025-01-11 01:28:25

尝试A< ::B>A

C内部,对B的非限定引用将获取所谓的注入类名,它是通过基类引入的A。由于 A 私有地从 B 继承,因此注入类名称也会随之而来并且也是私有的,因此 C 无法访问

另一天,另一种语言怪癖......

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文