<分区>
谁能给我一个没有子类型的继承示例,以及一个使用 C++ 的没有继承的子类型示例?
<分区>
谁能给我一个没有子类型的继承示例,以及一个使用 C++ 的没有继承的子类型示例?
最佳答案
根据 wikipedia ,子类型化,是为一种类型编写的程序部分也适用于其子类型时的关系:
Subtyping should not be confused with the notion of (class or object) inheritance from object-oriented languages;1 subtyping is a relation between types (interfaces in object-oriented parlance) whereas inheritance is a relation between implementations stemming from a language feature that allows new objects to be created from existing ones.
所以这里是没有继承的subtying的例子:
typedef int myint;
创建 int
的完美子类型 myint
。 enum mybool { myfalse=0, mytrue=1, mymorethantrue=10 };
创建 int
的子类型 mybool
。我可以为任何需要 int
的函数提供 mybool
。但是,我无法执行一些基本运算符。所以它不是一个完美的子类型,也不是最好的例子。 struct test { unsigned mytmp : 4; };
成员mytmp
是int
的完美子类型。我可以用 mytmp
对整数做任何事情,但它的值有限。 根据这个定义,也很容易找到没有子类型的继承的例子:
class Parent {};
class Child : private Parent {};
这里的Child
显然继承自Parent
。但是,为管理 Parent
而编写的代码将无法与 Child
一起使用(不可能进行替换),因为它是私有(private)继承的。
备注:在实践中,很多人倾向于将类型理解为类,将子类型理解为派生类。然而,C++ 标准确实在基本类型和被视为复合类型的类之间有所区别。并执行Liskov subsitition principle需要更深入地思考这两个相似但不相同的原则。
关于c++ - 您可以使用 C++ 创建继承而不进行子类型化吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569685/