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


请先看测试代码:

 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性。

相关内容