组成或继承 [英] Composition or Inheritance

查看:139
本文介绍了组成或继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个更多的思考问题。



让我说我有一个问题可以通过使用继承或组合来解决。

哪一个更好,为什么?

This is a more of a thought question.

Lets say I have a problem that could be solved by using either Inheritance or composition.
Which one is better and why?

推荐答案

通常如果你有选择,那么可能那个组合更好,因为它会更好地区分主要和次要对象的作用。



主要对象不会被本来可以继承但对主对象的外部用户没用的函数污染。



通常你想要仅为IS-A关系使用继承,或者如果必须覆盖虚函数。
Usually if you have the choicie, then probably that composition is better as it will better separate what main and secondary object do.

Main object will not be polluted by functions that would otherwise be inherited but are of no use to external user of the main object.

Typically you want to use inheritance only for IS-A relationship or if you have to override virtual functions.


这篇关于组成或继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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