91继承的概念 ◆类的继承是在现有类的基础之上,创建新类的 机制。称现有的类为基类,新建立的类为派生 类。 ■新类继承了基类的属性和行为 新类是基类的特殊情况。 ◆不必从“草稿”开始创建特殊的程序对象 ◆继承是处理“特殊情况”的面向对象编程机制 2021/2/24
2021/2/24 -11- 9.1 继承的概念 类的继承是在现有类的基础之上,创建新类的 机制。称现有的类为基类,新建立的类为派生 类。 ◼ 新类继承了基类的属性和行为 ◼ 新类是基类的特殊情况。 不必从“草稿”开始创建特殊的程序对象 继承是处理“特殊情况”的面向对象编程机制
派生类的定义格式 派生类只有 一个直接基 类为单继承 class派生类名:继承方式基类名 public: //派生类公有成员… private: //派生类私有成员 2021/2/24 12
2021/2/24 -12- 派生类的定义格式 class 派生类名:继承方式 基类名 { public: //派生类公有成员… private: //派生类私有成员… } 派生类只有 一个直接基 类为单继承
例:定义基类 shape class shape private: int m x,my;/位置 char m color;/颜色 public: void setposition (int x, int y); void setcolor(char color); int getxo; int geto char getcolor O } 2021/2/24
2021/2/24 -13 - 例: 定义基类shape class shape { private : int m_x ,m_y; //位置 char m_color; //颜色 public : void setposition (int x, int y); void setcolor (char color); int getx(); int gety(); char getcolor(); };
定义派生类(等边三角形类) class Triangle: public Shape public: Triangle(int x, int y, char color='R, float slen =1); float GetsideLength0 const; void SetTriangle(int x, int y, char color, float slen); void Draw prIvate float m_SideLength; 2021/2/24 -14
2021/2/24 -14- 定义派生类(等边三角形类) class Triangle: public Shape { public: Triangle(int x, int y, char color='R', float slen = 1); float GetSideLength() const; void SetTriangle(int x, int y, char color, float slen); void Draw(); private: float m_SideLength; };
派生新类: ◆ circle圆形 ◆ rectangle矩形 ◆ triangle三角形 shape 基类称为父类 派生类称为子类 circle rectangle triangle 2021/2/24 -15
2021/2/24 -15- 派生新类: circle 圆形 rectangle 矩形 triangle 三角形 基类称为父类 派生类称为子类 shape circle rectangle triangle