例5.12 class b protected public b0{x1=x2=5} class d1 public b ubli int fd 110 return x1 ∥lok,可以访问基类 protected成员 return x2 ∥lok,可以访问基类pubc成员 int fd 120 b bb: ∥ return bb.x1;类对象不可使用本类 protected成员 turn bb. x2 ∥lok,类对象可以使用基类 public,成员
例5.1.2 class b { protected: int x1; public: int x2; b() {x1 = x2 = 5;} }; class d1:public b { public: int fd11() { return x1; // ok,可以访问基类protected成员 return x2; // ok,可以访问基类public成员 } int fd12() { b bb; // return bb.x1; 类对象不可使用本类protected成员 return bb.x2; // ok,类对象可以使用基类public成员 } };
定义 Location-Point--Circle类层 次结构 class Location ∥位置类 protected ∥保护类成员 mx Pos mY Pos ∥在 Location派生类中可访问 pt Location( int X, int y) getX() } enum BOOLEAN FALSE, TRUE class Point: public Location ∥点类 protected 保护类成员 BOOLEAN vIsible ∥在 Point派生类中可访问 Public Point (int x, int y); BOOLEAN is Visible O show hide () Void moveTo():
定义Location—Point—Circle类层 次结构 class Location // 位置类 { protected: // 保护类成员 int mX_Pos, mY_Pos; // 在Location派生类中可访问 public: Location ( int x, int y); int getX ( ); int getY ( ); }; enum BOOLEAN { FALSE,TRUE }; class Point : public Location // 点类 { protected: // 保护类成员 BOOLEAN mVisible; // 在Point派生类中可访问 Public: Point(int x, int y); BOOLEANisVisible (); Void show ( ); Void hide ( ); Void moveTo ( ); };
class Circle: public Point 圆类 protected 保护类成员 int rAdius ∥圆半径,在Cice派生类中可访问 Public Circle(int X, int y, int r); ∥初始化圆 void show () ∥画圆 void hide (): ∥隐藏圆 void move To ( ∥移动圆 VO dd expand (int delta) ∥放大圆,半径为(r+deta) VO contract(int delta); ∥缩小圆,半径为(r- delta)
class Circle: public Point // 圆类 { protected: // 保护类成员 int mRadius; // 圆半径,在Circle派生类中可访问 Public: Circle(int x, int y, int r); // 初始化圆 void show ( ); // 画圆 void hide ( ); // 隐藏圆 void moveTo ( ); // 移动圆 void expand (int delta); // 放大圆,半径为(r + delta) void contract (int delta); // 缩小圆,半径为(r - delta) };
派生类中访问属性发生如下变化 冷1)基类的 private成员在派生类中是不可见的 冷2) private派生使基类中的非 private成员都成为派生 类中的私有成员; protected派生使基类的非 private 成员在派生类中都变为 protected成员; public派生使 基类的非 private成员在派生类中访问属性保持不变 冷3)不同的派生方式引起成员访问属性的改变,只能 降低,不能提高(如将 private成员提升为 protected 成员或pubc成员)。但是,C++允许在派生类中用 访问属性修饰符,恢复一个成员原来的访问属性
派生类中访问属性发生如下变化 ❖ 1) 基类的private成员在派生类中是不可见的 ❖ 2) private派生使基类中的非private成员都成为派生 类中的私有成员;protected派生使基类的非private 成员在派生类中都变为protected成员;public派生使 基类的非private成员在派生类中访问属性保持不变 ❖ 3) 不同的派生方式引起成员访问属性的改变,只能 降低,不能提高(如将private成员提升为protected 成员或public成员)。但是,C++允许在派生类中用 访问属性修饰符,恢复一个成员原来的访问属性
例514 class b protected int x1: nt x2: public int x3 int x4 class d private b ∥×1,x2,x3,x4将派生为 private成员 protected b:X1; ∥将x1恢复为 protected成员 public b: x3 ∥将x3恢复为 public成员 };
例5.1.4 class b { protected: int x1; int x2; public: int x3; int x4; … }; class d:private b // x1,x2,x3,x4 将派生为private成员 { protected: b::x1; // 将x1恢复为protected成员 public: b::x3; // 将x3恢复为public成员 … };