温馨提示:您可以点击下面的链接分享或打印转贴:C++语言常见问题解:#33 ~ #53全文。
he non-const member
function invocations between the object's construction and the const
member fn invocation are statically bound, and when every one of these
invocations is also "inline"d, and when the constructor itself is "inline"d,
and when any member fns the constructor calls are inline).
=====================
■□ 第12节:继承
=====================
Q50:「继承」对 C++ 来说很重要吗?
是的。
「继承」是抽象化资料型态(abstract data type, ADT)与 OOP 的一大分野。
========================================
Q51:何时该用继承?
做为一个「特异化」(specialization) 的机制。
人类以两种角度来抽象化事物:「部份」(part-of) 和「种类」(kind-of)。福特汽
车“是一种”(is-a-kind-of-a) 车子,福特汽车“有”(has-a) 引擎、轮胎……等
等零件。「部份」的层次随着 ADT 的流行,已成为软件系统的一份子了;而「继承
」则添入了“另一个”重要的软件分解角度。
========================================
Q52:怎样在 C++ 中表现出继承?
用 ": public" 语法:
class Car : public Vehicle {
//^^^^^^^^---- ": public" 读作「是一种」("is-a-kind-of-a")
//...
};
我们以几种方式来描述上面的关系:
* Car 是「一种」("a kind of a") Vehicle
* Car 乃「衍生自」("derived from") Vehicle
* Car 是个「特异化的」("a specialized") Vehicle
* Car 是 Vehicle 的「子类别」("subclass")
* Vehicle 是 Car 的「基底类别」("base class")
* Vehicle 是 Car 的「父类别」("superclass") (这不是 C++ 界常用的说法)
【译注】"superclass" 是 Smalltalk 语言的关键词。
========================================
Q53:把衍生类别的指针转型成指向它的基底,可以吗?
可以。
衍生类别是该基底类别的特异化版本(衍生者「是一种」("a-kind-of") 基底)。这
种向上的转换是绝对安全的,而且常常会发生(如果我指向一个汽车 Car,实际上我
是指向一个车子 Vehicle):
void f(Vehicle* v);
void g(Car* c) { f(c); } //绝对很安全;不需要转型
注意:在这里我们假设的是 "public" 的继承;后面会再提到「另一种」"private/
protected" 的继承。
========================================
function invocations between the object's construction and the const
member fn invocation are statically bound, and when every one of these
invocations is also "inline"d, and when the constructor itself is "inline"d,
and when any member fns the constructor calls are inline).
=====================
■□ 第12节:继承
=====================
Q50:「继承」对 C++ 来说很重要吗?
是的。
「继承」是抽象化资料型态(abstract data type, ADT)与 OOP 的一大分野。
========================================
Q51:何时该用继承?
做为一个「特异化」(specialization) 的机制。
人类以两种角度来抽象化事物:「部份」(part-of) 和「种类」(kind-of)。福特汽
车“是一种”(is-a-kind-of-a) 车子,福特汽车“有”(has-a) 引擎、轮胎……等
等零件。「部份」的层次随着 ADT 的流行,已成为软件系统的一份子了;而「继承
」则添入了“另一个”重要的软件分解角度。
========================================
Q52:怎样在 C++ 中表现出继承?
用 ": public" 语法:
class Car : public Vehicle {
//^^^^^^^^---- ": public" 读作「是一种」("is-a-kind-of-a")
//...
};
我们以几种方式来描述上面的关系:
* Car 是「一种」("a kind of a") Vehicle
* Car 乃「衍生自」("derived from") Vehicle
* Car 是个「特异化的」("a specialized") Vehicle
* Car 是 Vehicle 的「子类别」("subclass")
* Vehicle 是 Car 的「基底类别」("base class")
* Vehicle 是 Car 的「父类别」("superclass") (这不是 C++ 界常用的说法)
【译注】"superclass" 是 Smalltalk 语言的关键词。
========================================
Q53:把衍生类别的指针转型成指向它的基底,可以吗?
可以。
衍生类别是该基底类别的特异化版本(衍生者「是一种」("a-kind-of") 基底)。这
种向上的转换是绝对安全的,而且常常会发生(如果我指向一个汽车 Car,实际上我
是指向一个车子 Vehicle):
void f(Vehicle* v);
void g(Car* c) { f(c); } //绝对很安全;不需要转型
注意:在这里我们假设的是 "public" 的继承;后面会再提到「另一种」"private/
protected" 的继承。
========================================

文章评论