访问规则 派生类吸纳基类的数据成员及成员函数(隐性) 派生类的成员函数如何访问基类的数据成员和成 员函数?( publics继承) 0 2018 SEU. All rights reserved. 11
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 11 访问规则 派生类吸纳基类的数据成员及成员函数(隐性) 派生类的成员函数如何访问基类的数据成员和成 员函数?(public继承)
class Onet public: void setx (int a x= a; 1 void printo(cout < x;] private int x class Two: public Onel public void outputXO (print(:) void setAX( int a)( seta:) OK Int miano Twotwo two output () two. setAX(5) 0 2018, SEU. All rights reserved. 12
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 12 class One{ public: void setX (int a) {x = a;} void print() {cout << x;} private: int x; }; class Two: public One{ public: void outputX() {print();} }; Int mian() { Two two; two. outputX(); two.setAX(5); } void setAX( int a) { x = a ; } a) { setX(a) ; } Error OK
访问规则 派生类的成员函数如何访问基类的数据成员和成 员函数?( public继承) 可以访问基类中的非 private数据成员及成员函数 ●无法直接访问基类的 private成员 9可以通过基类中提供的非 private成员函数实现对基类 中 private数据成员进行修改 °通常派生类需要重新定义一些成员函数,以实现 派生类特有的功能及操作 0 2018, SEU. All rights reserved. 13
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 13 访问规则 派生类的成员函数如何访问基类的数据成员和成 员函数?(public继承) 可以访问基类中的非private数据成员及成员函数 无法直接访问基类的private成员 可以通过基类中提供的非private成员函数实现对基类 中private数据成员进行修改 通常派生类需要重新定义一些成员函数,以实现 派生类特有的功能及操作
Topics o 12.1 Introduction 12.2 Base Classes and derived classes o 12.3 Protected Members o 12. 4 Relationship between Base Classes and Derived classes o 12.5 Constructors and destructors in derived Classes o 12.6 public, protected and private Inheritance o 12.7 Software Engineering with Inheritance 0 2018, SEU. All rights reserved. 14
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 14 Topics 12.1 Introduction 12.2 Base Classes and Derived Classes 12.3 Protected Members 12.4 Relationship between Base Classes and Derived Classes 12.5 Constructors and Destructors in Derived Classes 12.6 public, protected and private Inheritance 12.7 Software Engineering with Inheritance
12.3 Protected members 需求: 类有两种用户:类实例和派生类 °如何使派生类可以访问基类的成员,同时又能够使基 类的成员不被类的实例用户访问? 基类的 protected成员可以被派生类的成员和友元访 cass a jaic int maino private protected [A a; int x,yi ax=9 return class B: public A i void printXYO cout<<x<<y;丹 error C2248: cannot access private member declared in class 'A } 0 2018. SEU. All rights reserved. 15
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 15 12.3 Protected Members 需求: 类有两种用户:类实例和派生类 如何使派生类可以访问基类的成员,同时又能够使基 类的成员不被类的实例用户访问? 基类的protected成员可以被派生类的成员和友元访 问class A { private: int x,y; }; class B: public A { void printXY() {cout<<x<<y;} }; int main() { A a; a.x=9; return 0; } public protected error C2248: cannot access private member declared in class 'A