公有继承
公有继承 public:
当类的继承方式为公有继承时,基类的公有和保护成员的访问属性在派生类中 不变,而基类的私有成员不可访问。 即基类的公有成员和保护成员被继承到派生类中仍作为派生类的公有成员和保护成员。派生类的其他成员可以直接访问它们。无 论派生类的成员还是派生类的对象都无法访问基类的私有成员。
1 #include <iostream>
2
3 using namespace std;
4
5 class info {
6 public:
7 int getter(void) {
8 return age;
9 }
10
11 void setter(int a) {
12 age = a;
13 }
14 void pri(void) {
15 cout << age << endl;
16 }
17
18 protected:
19 int prot;
20
21
22 private: // 派生类不可访问
23 int age;
24 };
25
26 class info_j :public info {
27 public:
28 void info_pri(void) {
29 cout << num << endl;
30 }
31
32 void set_pri_prot(int a) {
33 info::prot = a;
34 cout << info::prot << endl;
35 }
36
37 private:
38 int num;
39 };
40
41 int main(void) {
42
43 info_j infoj; //定义一个派生类
44 infoj.setter(666); //派生类直接访问基类的public
45 infoj.pri();
46 infoj.set_pri_prot(777); //派生类直接访问基类的protected
47
48 system("pause");
49
50 return 0;
51 }
笔记