面向对象的编程方法.pptVIP

  • 5
  • 0
  • 约 49页
  • 2017-09-06 发布于重庆
  • 举报
继承与派生 类的继承与派生 保持已有类的特性而构造新类的过程称为继承。 在已有类的基础上新增自己的特性而产生新类的过程称为派生。 被继承的已有类称为基类(或父类)。 派生出的新类称为派生类。 继承与派生问题举例 继承与派生的目的 继承的目的:实现代码重用。 派生的目的:当新的问题出现,原有程序无法解决(或不能完全解决)时,需要对原有程序进行改造。 派生类的定义 class 派生类名:继承方式 基类名1, …. { 成员定义; } 多继承:一个派生类有多个基类; 单继承:一个派生类只有一个基类。 继承方式 共有三种继承方式:公有继承(public),私有继承(private),保护继承(protected)。 继承方式指定派生类成员以及类外对象对继承来的成员的访问权限。 不同继承方式的影响主要体现在: 1、派生类成员对基类成员的访问控制。 2、派生类对象对基类成员的访问控制。 公有继承(public) 基类的public和protected成员的访问属性在派生类中保持不变,但基类的private成员不可访问。 派生类中的成员函数可以直接访问基类中的public和protected成员,但不能访问基类的private成员。 派生类的对象只能访问基类的public成员。 私有继承(private) 基类的public和protected成员都以private身份出现在派生类中,但基类的private成员不可访问。 派生类中的成员函数可以直接访问基类中的public和protected成员,但不能访问基类的private成员。 派生类的对象不能访问基类中的任何成员。 保护继承(protected) 基类的public和protected成员都以protected身份出现在派生类中,但基类的private成员不可访问。 派生类中的成员函数可以直接访问基类中的public和protected成员,但不能访问基类的private成员。 派生类的对象不能访问基类中的任何成员. 公有继承举例 class Location { public: void InitL(int xx,int yy); void Move(int xOff,int yOff); int GetX() {return X;} int GetY() {return Y;} private: int X,Y; }; void Location::InitL(int xx,int yy) { X=xx; Y=yy; } void Location::Move(int xOff,int yOff) { X+=xOff; Y+=yOff; } class Rectangle:public Location //派生类 { public: void InitR(int x,int y,int w,int h); int GetH() {return H;} int GetW() {return W;} private: int W,H; }; void Rectangle::InitR(int x,int y,int w,int h) { InitL(x,y); //派生类直接访问原公有成员 W=w; H=h; } int main() { Rectangle rect; rect.InitR(2,3,20,10); rect.Move(3,2); coutrect.GetX()‘,’ //对象访问原公有成员 rect.GetY(), rect.GetH(), rect.GetW()endl; return 0; } 私有继承举例 class Rectangle:private Location { public: void InitR(int x,int y,int w,int h); void Move(int xOff,int yOff); int GetX() {coutX=;return Location:: GetX();} int GetY() {cout”Y=; return Location::GetY();} int GetH() {cout”H=; return H;} int GetW() {cout”W=; return W;} private: int W,H; }; void Rectangle::InitR(int x,int y,int w,int h) { InitL(x,y); W=w; H=h; } v

文档评论(0)

1亿VIP精品文档

相关文档