歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++ virtual 與“基類"和"派生類”的訪問控制

C++ virtual 與“基類"和"派生類”的訪問控制

日期:2017/3/1 10:28:18   编辑:Linux編程

請先看測試代碼:

 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性。
Copyright © Linux教程網 All Rights Reserved