第十章 虛擬函式和多型 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
您可能关注的文档
- 素食者容易误食的成分.DOC
- 紧凑型空间外差成像光谱仪设计.PDF
- 紫外光区C#分子激光诱导荧光光谱-光谱学与光谱分析.PDF
- 紫云英非特异性转脂蛋白AsIB259的体外酶活性及-华中农业大学学报.PDF
- 紫外吸收光谱常用于共轭体系的定量分析.PPT
- 紫外线照度计UITL201DigitalUVIntensityMeter.PDF
- 紫杉醇聚氰基丙烯酸正丁酯纳米粒制备研究-南方医科大学学报.PDF
- 紫色石蕊和无色的酚酞试液是常用的酸碱指示剂-玉田三中网络U盘.PPT
- 紫胶蚧与寄主植物无机盐含量关系初步研究-生态学杂志.PDF
- 紫草乳膏提取工艺研究-世界中医药.PDF
- 河北盐山中学等校2025-2026学年上学期高三一模化学试卷(含解析).docx
- 河北正定中学2025-2026学年高一上学期期末考试物理试卷(含解析).docx
- 河北张家口市怀安县2025-2026学年第一学期期末教学综合评价八年级地理试卷(含解析).docx
- 河南安阳市殷都区2025-2026学年第一学期期末教学质量检测七年级地理试卷(含解析).docx
- 河南安阳市滑县2025一2026学年第一学期期末学业质量监测八年级地理试题(含解析).docx
- 河南安阳市林州市2025-2026学年上学期期末考试高一政治试题(含解析).docx
- 河南焦作市武陟县第一中学2025-2026学年高一上学期1月月考语文试卷(含解析).docx
- 河南济源市2025-2026学年上学期期末学业质量调研七年级历史试卷(含解析).docx
- PICC导管并发症的紧急处理与护理.pptx
- 河南鹤壁市2025-2026学年高二上学期期末考试生物试题(含解析).docx
原创力文档

文档评论(0)