为什么从一个具体的类派生是一个糟糕的设计 [英] why derive from a concrete class is a poor design

查看:161
本文介绍了为什么从一个具体的类派生是一个糟糕的设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读关于非虚拟接口模式的信息:Herb Sutter正在谈论为什么虚拟函数必须在大多数的案件,在某些情况下保护,从不公开。



但在文章结尾处,他写道:


不要从具体类派生。或者,正如Scott Meyers在更有效的C ++的项目33中所提出的,使非叶类抽象化。 (不可否认,它可能发生在实际中 - 在别人写的代码中,当然不是由你! - 在这种情况下,你可能必须有一个公共的虚拟析构函数,以适应已经是一个糟糕的设计。并修复设计,但如果可以。)


但我不明白为什么这是一个糟糕的设计

解决方案

从一个具体类型继承的一个问题是,它是否会产生一些歧义,指定某个类型的代码是否真的想要一个对象特定具体类型,或者希望具有以具体类型行为方式行为的类型的对象。这种区别在C ++中是至关重要的,因为在许多情况下,对某种类型的对象正确工作的操作将在派生类型的对象上失败。在Java和.NET中,可以使用特定类型的对象但不能使用派生类型的对象的情况较少。因此,从具体类型继承不是几乎有问题。即使在那里,密封具体类继承抽象类,并使用抽象类类型除了在构造函数调用(必须使用具体类型),将使得更容易改变类层次结构的部分,而不破坏代码。 / p>

I was reading about NonVirtual Interface pattern: Herb Sutter is talking about why virtual function must be private in most of the case, protected in some case and never public.

But at the end of the article he write:

Don't derive from concrete classes. Or, as Scott Meyers puts it in Item 33 of More Effective C++,[8] "Make non-leaf classes abstract." (Admittedly, it can happen in practice - in code written by someone else, of course, not by you! - and in this one case you may have to have a public virtual destructor just to accommodate what's already a poor design. Better to refactor and fix the design, though, if you can.)

But I don't understand why this is a poor design

解决方案

A problem with inheriting from a concrete type is that it creates some ambiguity as to whether code which specifies a certain type really wants an object of the specific concrete type, or wants an object of a type which behaves in the fashion that the concrete type behaves. This distinction is vital in C++, since there are many cases where operations which will work correctly on objects of a certain type will fail badly on objects of derived types. In Java and .NET, there are many fewer situations where one can use an object of a particular type, but could not use an object of a derived type. As such, inheriting from a concrete type isn't nearly as problematical. Even there, however, having sealed concrete classes which inherit from abstract classes, and using the abstract class types everywhere except in constructor invocations (which must use the concrete types) will make it easier to change parts of the class hierarchy without breaking code.

这篇关于为什么从一个具体的类派生是一个糟糕的设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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