按键盘上方向键 ← 或 → 可快速上下翻页,按键盘上的 Enter 键可回到本书目录页,按键盘上方向键 ↑ 可回到本页顶部!
————未阅读完?加入书签已便下次继续阅读!
三种修饰词。一般而言成员变量尽量声明为 ,成员函数则通常声明为
publ ic m_color pr ivate setcolor
。上例的 既然声明为 ,我们势必得准备一个成员函数 ,
供外界设定颜色用。
pr ivate
把资料声明为 ,不允许外界随意存取,只能透过特定的接口来操作,这就是对象
导向的封装(encapsulation )特性。
基础类别与衍生类别 :谈继承(Inheritance)
C struct
其它语言欲完成封装性质,并不太难。以 为例,在结构( )之中放置资料,以
及处理资料的函数的指针(function pointer ),就可得到某种程度的封装精神。
C++ 神秘而特有的性质其实在于继承。
矩形是形,椭圆形是形,三角形也是形。苍蝇是昆虫,蜜蜂是昆虫,蚂蚁也是昆虫。是
的,人类习惯把相同的性质抽取出来,成立一个基础类别(base class ),再从中衍化出
衍生类别(derived class )。所以,关于形状,我们就有了这样的类别阶层:
Shape
Shape
Ellipse Triangle Rectangle
Ellipse Triangle Rectangle
Circle Square
Circle Square
注意:衍生类别与基础类别的关系是“IsKindOf” 的关系。也就是说,
「是一种」 , 「是一种」 ;
Circle Ellipse Ellipse Shape
「是一种」 , 「是一种」 。
Square Rectangle Rectangle Shape
57
…………………………………………………………Page 120……………………………………………………………
#0001 class CShape // 形状
#0002 {
#0003 private:
#0004 int m_color;
#0005
#0006 public:
#0007 void setcolor(int color) { m_color = color; }
#0008 };
#0009
#0010 class CRect : public CShape // 矩形是一种形状
#0011 { // 它会继承 m_color 和 setcolor()
#0012 public:
#0013 void display() { 。。。 }
#0014 };
#0015
#0016 class CEllipse : public CShape // 椭圆形是一种形状
#0017 { // 它会继承 m_color 和 setcolor()
#0018 public:
#0019 void display() { 。。。 }
#0020 };
#0021
#0022 class CTriangle : public CShape // 三角形是一种形状
#0023 { // 它会继承 m_color 和 setcolor()
#0024 public:
#0025 void display() { 。。。 }
#0026 };
#0027
#0028 class CSquare : public CRect // 四方形是一种矩形
#0029
#0030 public:
#0031 void display() { 。。。 }
#0032 };
#0033
#0034 class CCircle : public CEllipse // 圆形是一种椭圆形
#0035 {
#0036 public:
#0037 void display() { 。。。 }
#0038 };
于是你可以这么动作:
CSquare square;
CRect rect1; rect2;
CCircle circle;
square。setcolor(1); // 令 square。m_color = 1;
58
…………………………………………………………Page 121……………………………………………………………
square。display (); // 调用CSquare::display
rect1。setcolor (2); // 于是rect1。m_color = 2
rect1。display (); // 调用CRect::display
rect2。setcolor (3); // 于是rect2。m_color = 3
rect2。display (); // 调用CRect::display
circle。setcolor (4); // 于是circle。m_color = 4
circle。display (); // 调用CCircle::display
注意以下这些事实与问题:
1。 所有类别都由CShape 衍生下来,所以它们都自然而然继承了CShape 的成员,
包括变量和函数。也就是说,所有的形状类别都「暗自」具备了m_color 变量
和setcolor 函数。我所谓暗自(implicit ),意思是无法从各衍生类别的声明中
直接看出来。
2。 两个矩形对象rect1 和rect2 各有自己的m_color,但关于setcolor 函数却是
CRect::setcolor CShape::setcolor
共享相同的 (其实更应该说是 )。我用这张图表
示其间的关系:
这个this 参数是编译器自行为我们加上的,
“ ”
对象rect1 对象rect2 所以我说它是个 隐藏指针 。
CRect::setcolor(int color;
m_color m_color
CRect* this)
{
this…》m_color = color;
}
this 指针 this 指针
rect1。setcolor rect2。setcolor CRect::setcolor
和 调用的都是 ,
后者之所以能分别处理不同对象的成员变量,完全是靠一个隐藏的this 指针。
rect1 setcolor
让我替你问一个问题:同一个函数如何处理不同的资料?为什么 。 和
rect2 setcolor CRect setcolor CShape setcolor
。 明明都是调用 :: (其实也就是 ::