继承的介面与实作.PPT

第十章 虛擬函式和多型 10.1 簡介 虛擬函式和多型 virtual functions and polymorphism 可以設計並實作出更有彈性(可擴展性)的系統 程式可以用更一般化的方式來處理現存的所有階層中的物件。 例子 使用抽象基本類別 Shape 定義一般介面 (functionality) Point, Circle 和 Cylinder 繼承自Shape 類別Employee 10.2 繼承階層中的物件關係  Previously (Section 9.4), Circle繼承自Point 使用成員函式處理 Point and Circle Now 使用base-class/derived-class 指標呼叫成員函式 引用 virtual functions Key concept 衍生類別物件可視為基本類別物件 “is-a” relationship 基本類別物件則不是衍生類別物件 10.2.1 從衍生類別物件來呼叫基本類別的函式 Aim pointers (base, derived) at objects (base, derived) Base pointer aimed at base object 基本類別指標指向衍生類別物件 Both straightforward 從衍生類別物件的位址指定給基本類別的指標 是”一種”關係” Circle 是一種 Point 會呼叫基本類別的函式 函式呼叫依據指標型別決定呼叫函式 而非依據指標的內容呼叫函式 可使用virtual functions 來改變(more later) 1 // Fig.?10.1: point.h 2 // Point class definition represents an x-y coordinate pair. 3 #ifndef POINT_H 4 #define POINT_H 5 6 class Point { 7 8 public: 9 Point( int = 0, int = 0 ); // default constructor 10 11 void setX( int ); // set x in coordinate pair 12 int getX() const; // return x from coordinate pair 13 14 void setY( int ); // set y in coordinate pair 15 int getY() const; // return y from coordinate pair 16 17 void print() const; // output Point object 18 19 private: 20 int x; // x part of coordinate pair 21 int y; // y part of coordinate pair 22 23 }; 24 25 #endif 1 // Fig.?10.2: point.cpp 3 #include iostream 5 using std::cout; 7 #include point.h // Point class definition 9 // default constructor 10 Point::Point( int xValue, int yValue ) : x( xValue ), y( yValue ) { 13 // empty body 15 } 17 // set x in coordinate pair 18 void Point::setX( int xValue ) { 20 x = xValue; } 24 // return x from coordinate pair 25 int Point::getX() const { 27 return x; 29 } 31 // set y in coordinate pair 32 void Point::setY( int yValue ) { 34 y = yValue; } 38 // return y from coordi

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档