密封类实现查询
我正在阅读 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它之所以有效,是因为由于虚拟继承的工作方式,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.