C++_练习—继承_私有继承

私有继承


私有继承:当私有继承时,基类的公有和保护成员变成派生类的私有成员,私有成员不可直接访问

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class info {
 6 public:
 7     void setter(int a, int b) {
 8         num = a;
 9         age = b;
10     }
11 
12     void pri(void) {
13         cout << num << endl;
14         cout << age << endl;
15     }
16 
17 protected:
18     int num;
19 
20 private:
21     int age;
22 
23 };
24 
25 class infoj :private info{
26 public:
27     void infoj_pri(int a,int b) {
28         setter(a, b);
29         pri();
30     }
31 
32 protected:
33     int num;
34 
35 private:
36     int age;
37 };
38 
39 
40 
41 int main(void)
42 {
43     infoj info1;
44 
45     /* info1.setter(1,2);   看!从基类继承过来的公有成员,存储在自己的private
46                             同理也是,通过infoj_pri间接访问基类的公有成员
47     */
48 
49     info1.infoj_pri(66, 77);   // 由于继承过来基类公有的放在派生类私有,则可以通过派生类公有间接访问!
50 
51     system("pause");
52 
53     return 0;
54 }

笔记


猜你喜欢

转载自www.cnblogs.com/panda-w/p/11368014.html