加入收藏 | 设为首页 | 会员中心 | 我要投稿 开发网_郴州站长网 (http://www.0735zz.com/)- 云通信、区块链、物联设备、云计算、站长网!
当前位置: 首页 > 教程 > 正文

C++ using声明获得的权限介绍

发布时间:2021-12-16 13:42:58 所属栏目:教程 来源:互联网
导读: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声明。 下
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方法。

(编辑:开发网_郴州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读