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

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

问题描述

这个主题有足够的信息。例如,这个线程对我很清楚:私人,公共和受保护的继承在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 in C++

除了一点;为什么有用?

Except one point; Why is it useful?

推荐答案

使用公共继承来反映 。这是继承的主要用途,特别是与虚函数结合使用。它允许重用接口,不仅是旧代码的新代码,而且重新使用旧代码的旧代码!

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 。这是一个通常过度使用的模式,通常可以通过组合(具有作为数据成员的将成为基础类)来达到等效目标。另一个缺点是,您可以轻松地拥有相同基类的多重继承(删除两次或多次),导致所谓的 Diamond问题

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天全站免登陆