C ++为什么要使用公共,私有或受保护的继承? [英] C++ why use public, private or protected inheritance?

查看:95
本文介绍了C ++为什么要使用公共,私有或受保护的继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关此主题的足够信息。例如,这个帖子对我来说非常清楚:私密,公共和受保护的继承

Well there is enough information about this subject. For example this thread was very clear to me: Difference between private, public, and protected inheritance

除了一点之外;为什么它有用?

Except one point; Why is it useful?

推荐答案

使用公共继承来反映 is-a关系即可。这是继承的主要用途,特别是与虚函数结合使用。它允许重新使用接口,不仅可以通过新代码重用旧代码,还可以通过旧代码重用新代码! (因为在运行时调度虚函数)。

Use public inheritance to reflect an is-a relationship. This is the main use for inheritance, especially in combination with virtual functions. It allows re-use of interface, not just of old code by new code, but also re-use of new code by old code! (because of virtual function dispatch at runtime).

在特殊情况下,使用私有继承来反映 is-implemented-in -terms-of relationship 。这是一种常用的过度使用模式,通常可以通过组合达到相同的目标(将可能的基类作为数据成员)。另一个缺点是你可以轻松地对同一个基类进行多次继承(删除两次或更多次),从而导致所谓的钻石问题

In exceptional circumstances, use private inheritance to reflect an is-implemented-in-terms-of relationship. This is a commonly overused pattern, often the equivalent goal can be reached through composition (having the would-be base class as a data member). Another drawback is that you can easily have multiple inheritance of the same base class (twice or more removed) leading to the so-called Diamond Problem.

避免使用受保护的继承,它表明您的类接口是客户端依赖的(派生的)班级与世界)。通常这是由于具有多个责任的类,这表明重构成单独的类是合适的。

Avoid using protected inheritance, it suggest that your class interface is client-dependent (derived classes versus the world). Often this is due to classes having multiple responsiblities, suggesting a refactoring into separate classes is appropriate.

这篇关于C ++为什么要使用公共,私有或受保护的继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆