2014-07-27 星期日 18:10:56
重温下c++ primer,随意记录。
1、基类protected成员
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
66
67
68
69
70
71
72
73
74
75
76
77
|
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <utility>
#include <string>
using
namespace
std;
/*
如果没有继承,
类只有两种用户:
1:类本身的成员
2:类的用户(instance或有效的ptr&ref)
有继承
3:derive:public/protected/private均可
derive可以访问base protected,不可以访问base private
希望禁止derive访问的成员应该设为 private
希望提供derive实现所需方法或数据的成员应设为 protected。
所以
base提供给derive的接口应该是
protected 成员和 public 成员的组合。
*/
class
base
{
public
:
base():m_base(3){}
virtual
~base(){}
protected
:
int
m_base;
};
class
derive:
private
base
{
public
:
derive():m_derive(4){}
public
:
void
access(
const
base& refb,
const
derive& refd)
{
/*
此外,protected 还有另一重要性质:
派生类只能通过派生类对象访问其基类的 protected 成员,
派生类对其基类类型对象的 protected 成员没有特殊访问权限。
*/
//cout << "refb.m_base : "<< refb.m_base<< endl;
/*
15.2.2. protected 成员
可以认为 protected 访问标号是 private 和 public 的混合:
.像 private 成员一样,protected 成员不能被类的用户访问。
.像 public 成员一样,protected 成员可被该类的派生类访问。
*/
cout <<
"refd.m_base : "
<< refd.m_base<< endl;
cout <<
"refd.m_derive: "
<< refd.m_derive<< endl;
}
protected
:
int
m_derive;
};
int
main (
int
argc,
char
*argv[])
{
#if 1
base b;
base *pb =
new
base();
//cout << "m_base : "<< b.m_base<< endl;
derive d;
d.access(b, d);
#endif
return
0;
}
|