C++_练习—继承_保护继承


 保护继承


protected:保护继承

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

 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     int getter(void) {
13         int a = age;
14         return a;
15     }
16 
17     void pri(void) {
18         cout << num << endl;
19         cout << age << endl;
20     }
21 
22 protected:
23     int num;
24 
25 private:
26     int age;
27 };
28 
29 class info_j : protected info{
30 public:
31     void infoj_pri(void) {
32         setter(66,77);     // 从基类继承过来的,存储在自己的protected
33         pri();             // 同理也是,通过pri间接访问了基类的私有成员
34     }
35 
36 protected:
37     int num;
38 
39 private:
40     int age;
41 
42 };
43 
44 int main(void)
45 {
46     info_j infoj;
47 
48     /*infoj.setter()  看!报错无法直接调用,原因是基类的公有保护成员都变成派生类的保护成员,
49                       只能通过派生类的公有成员间接调用! 
50     */
51 
52     infoj.infoj_pri();
53 
54     system("pause");
55 
56     return 0;
57 }

 笔记


猜你喜欢

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