密封类实现查询

发布于 2024-10-09 17:49:59 字数 549 浏览 0 评论 0原文

我正在阅读 http://www2.research.att.com/~ 上的 C++ 常见问题解答bs/bs_faq2.html ,当我遇到这段代码来实现“密封”类时:

class Base{
    public:
      friend class A;
    private:
      Base(){cout<<"Base constructor called";}
};

class A : public virtual Base{
   public:
     A(){cout<<"A const called";}
};

class B : private A{};

int main(){
  A a;
  //B b;
  return EXIT_SUCCESS;
}

我不明白如何通过使用 virtual 关键字来实现“密封”类效果。如果我删除 virtual 关键字,那么它就没有“密封”效果。为什么?

I was reading the C++ faqs on http://www2.research.att.com/~bs/bs_faq2.html , when i came accross this code to implement a 'sealed' class:

class Base{
    public:
      friend class A;
    private:
      Base(){cout<<"Base constructor called";}
};

class A : public virtual Base{
   public:
     A(){cout<<"A const called";}
};

class B : private A{};

int main(){
  A a;
  //B b;
  return EXIT_SUCCESS;
}

I did not understand how by using the virtual keyword, 'sealed' class effect is achieved. If i remove the virtual keyword, then it has no 'sealed' effect. Why?

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

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

发布评论

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

评论(1

探春 2024-10-16 17:49:59

它之所以有效,是因为由于虚拟继承的工作方式,B 必须构造 Base,但它不能,因为 Base 的构造函数是私有的。只有 A 可以构造 Base。在正常继承中,B 构造 A,A 构造 Base,这很好,因为 A 可以构造 Base,B 可以构造 A。

It works because due to the way virtual inheritance works, B must construct Base- which it can't, because Base's constructor is private. Only A can construct Base. In normal inheritance, B constructs A, which constructs Base, which is fine because A can construct Base and B can construct A.

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