您的位置:首页 > 编程语言 > C语言/C++

C++ virtual 与"基类"和"派生类"的访问控制

2019-07-31 08:12 155 查看
原文链接:http://www.cnblogs.com/yaohwang/archive/2011/11/27/2367988.html

请先看测试代码:

1 #include "stdafx.h"
2 #include <iostream>
3
4 using namespace std;
5
6 //基类
7 class Base
8 {
9 public:
10 void get() const;
11 private:
12 virtual void dosth() const;
13 };
14
15 void Base::get() const
16 {
17 dosth();
18 }
19
20 void Base::dosth() const
21 {
22 cout << "Base dosth" << endl;
23 }
24
25 //派生类
26 class Derived1: public Base
27 {
28 public:
29 virtual void dosth() const;
30 };
31
32 void Derived1::dosth() const
33 {
34 cout << "Derived1 dosth" << endl;
35 }
36
37 int _tmain(int argc, _TCHAR* argv[])
38 {
39 Base b;
40 Derived1 d1;
41 b.get();
42 d1.get();
43 //b.dosth();
44 d1.dosth();
45 return 0;
46 }



1、d1.get()和d1.dosth()能获得相同结果。

2、基类中的private virtual,我们可以在派生类中实现。

3、基类中的private virtual,我们在派生类的public中实现,并不影响它的virtual性。

转载于:https://www.cnblogs.com/yaohwang/archive/2011/11/27/2367988.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: