C++类的3种继承方式

简单地说下C++类的3种继承方式,分别是public继承,protected继承,private继承。

最常用的还是public继承。class默认的是private继承,它的member如果没写权限也是默认

private。struct则相反,默认的是public继承。结合下面的图示和代码,对C++的继承就有了

比较清晰的认识了。

img

继承之后,derived class 继承过后的member的属性就是图中所示。

代码主要从:

1.基类成员对其对象的可见性:

  1. 基类成员对派生类的可见性:

  2. 基类成员对派生类对象的可见性:

这3个方面谈的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>  

class base{
public:
base(){
a = 0;
b = 1;
c = 2;
}
int a;
protected:
int b;
private:
int c;
};

class derived1 : public base{//public继承
public:
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b<<std::endl;
// std::cout<<base::c;//不能访问
}
};
class derived2 : protected base{//protected继承
public:
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b<<std::endl;
// std::cout<<base::c;//不能访问
}
};
class derived3 : private base{//private继承
public:
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b<<std::endl;
// std::cout<<base::c;//不能访问
}
};
class derived4 : public derived3{//base的member不能被private继承的派生类的子类访问
public:
void fun(){
// std::cout<<a;
}
};
class derived5 : base{//默认private继承
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b;
// std::cout<<base::c;//不能访问
}
};
int main(void)
{
base b1;
derived1 d1;
derived2 d2;
derived3 d3;
d1.fun();
d2.fun();
d3.fun();
std::cout<<b1.a;//base class Object只能访问public member
std::cout<<d1.a;//public继承时 derived class Object只能访问base class的public member
//std::cout<<d1.b<<d1.c;//不能访问
//std::cout<<d2.a<<d2.b;//protected继承时 derived class Object不能问访base class的member
//std::cout<<d3.a;//private继承时 derived class Object不能问访base class的member
return 0;
}

纸短情长啊文章结束了但我们的故事还在继续
坚持原创技术分享,您的支持将鼓励我继续创作!