C++ using声明获得的权限简析

using声明,形式如下:

using 作用域名::名字

还是先举个例子:

 1 class Base
2 {
3 public:
4 int pubi;
5 void pub()
6 {
7 };
8 };
9
10 class Derived1:public Base
11 {
12 public:
13 using Base::pub;
14 };

其中 的using Base::pub就是using声明。

下面再来看看测试代码:

 1 #include "stdafx.h"
2 #include <iostream>
3
4 using namespace std;
5
6 class Base
7 {
8 public:
9 int pubi;
10 void pub()
11 {
12 cout << "Base public" << endl;
13 };
14 protected:
15 int proi;
16 void pro(){};
17 private:
18 int prii;
19 void pri(){};
20 };
21
22 class Derived1:public Base
23 {
24 public:
25 using Base::pub;
26 void pub(int i)
27 {
28 cout << "Derived1 public" << endl;
29 }
30 };
31
32 class Derived2:public Base
33 {
34 public:
35 void pub(int i)
36 {
37 cout << "Derived2 public" << endl;
38 }
39 protected:
40 using Base::pub;
41 };
42
43 class Derived3:public Base
44 {
45 public:
46 using Base::pro;
47 void pub(int i)
48 {
49 cout << "Derived1 public" << endl;
50 }
51 void test3()
52 {
53 pub();
54 }
55 private:
56 using Base::pub;
57 };
58
59 int _tmain(int argc, _TCHAR* argv[])
60 {
61 Derived1 d1;
62 d1.pub();
63 Derived2 d2;
64 //d2.pub();
65 Derived3 d3;
66 /*d3.pro();*/
67 return 0;
68 }

1、Derived1、Derived2和Derived3中的using Base::pub,在最后的main函数里面可以看出using声明分别做了以下事情:

在Derived1中让Base的public方法保持public,由此我们可以通过Derived1的对象d1访问Base的public pub方法。

在Derived2中让Base的public方法变为protected,这样通过Derived2的对象d2无法访问protected pub方法。

在Derived2中让Base的private方法变为public,仿佛能通过Derived3的对象d3访问public pub方法,能通过编译,但是执行时不会返回任何结果。

2、在Derived3中我们又可以看出,即便是在private中用using声明。也可以在整个Derived3作用域中(此处为public中的test3方法)访问using声明的pub方法。

原文链接: https://www.cnblogs.com/yaohwang/archive/2011/11/27/2367989.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ using声明获得的权限简析

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/37385

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午2:02
下一篇 2023年2月8日 下午2:02

相关推荐