继承可能在c++
来源:互联网 发布:mmd古风动作数据 编辑:程序博客网 时间:2024/05/16 17:20
在继承之前的教训,我们已经使我们所有的公共数据成员为了简化的例子。在本节中,我们将讨论访问说明符的作用在继承过程中,以及涵盖不同类型的继承可能在c++。
至此,您已经看到了私人和公共访问说明符,决定谁可以访问类的成员。作为一个快速复习,公共成员可以被任何人访问。私有成员只能由同一个类的成员函数访问。请注意,这意味着派生类不能访问私有成员!
1
2
3
4
5
6
7
class
Base
{
private
:
int
m_nPrivate;
// can only be accessed by Base member functions (not derived classes)
public
:
int
m_nPublic;
// can be accessed by anybody
};
当处理继承类,事情变得更加复杂。
首先,还有第三个访问说明符,我们还没有谈论,因为它是唯一有用的遗传背景。受保护的访问说明符限制访问同一个类的成员函数,或派生类。
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
class
Base
{
public
:
int
m_nPublic;
// can be accessed by anybody
private
:
int
m_nPrivate;
// can only be accessed by Base member functions (but not derived classes)
protected
:
int
m_nProtected;
// can be accessed by Base member functions, or derived classes.
};
class
Derived:
public
Base
{
public
:
Derived()
{
// Derived's access to Base members is not influenced by the type of inheritance used,
// so the following is always true:
m_nPublic = 1;
// allowed: can access public base members from derived class
m_nPrivate = 2;
// not allowed: can not access private base members from derived class
m_nProtected = 3;
// allowed: can access protected base members from derived class
}
};
int
main()
{
Base cBase;
cBase.m_nPublic = 1;
// allowed: can access public members from outside class
cBase.m_nPrivate = 2;
// not allowed: can not access private members from outside class
cBase.m_nProtected = 3;
// not allowed: can not access protected members from outside class
}
第二,当一个派生类从基类继承,访问说明符可能会改变取决于继承的方法。有三种不同的方法从其他类继承类:公共,私人和保护。
这样做,只需指定你想要哪种类型的访问在选择继承的类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Inherit from Base publicly
class
Pub:
public
Base
{
};
// Inherit from Base privately
class
Pri:
private
Base
{
};
// Inherit from Base protectedly
class
Pro:
protected
Base
{
};
class
Def: Base
// Defaults to private inheritance
{
};
0 0
- 继承可能在c++
- 如何在C#中实现继承?
- c继承
- C++----------------继承
- 【c#】继承
- C++:继承
- C++::继承
- [C++]继承
- 【C++】继承
- 【C#】继承
- 【c++】继承
- 【C++】继承
- c#-继承
- 【C++】 继承
- 【C#】继承
- C++|继承
- 【C++】继承
- 《Effective C#》Item 19:推荐在继承中使用接口
- Codeforces Round #246 (Div. 2) A. Choosing Teams
- oracle根据列名查找包含此列名的表的名称
- expression动态构成
- CCAT-S1试题-图书管理系统
- 大斐波那契数
- 继承可能在c++
- web安全学习笔记之-点击劫持
- 使用Application Loader上传APP流程解读[APP发布]
- 私有继承
- ubuntu 14.04 安装 32位兼容库
- 这图代表什么?能看懂吗
- Rational Rose中的四种视图
- 页面js禁用鼠标右键
- 基于Struts+Hibernate开发过程中遇到的错误