C++ using用法
#include <iostream> using namespace std; class ClassOne { public:int w; protected:int a; }; class ClassTwo { public:using ModuleType = ClassOne; }; template <typename ClassType>class ClassThree : private ClassType { public:using typename ClassType::ModuleType;ModuleType m;ClassThree() = default;virtual ~ClassThree() = default; }; void main() {ClassThree<ClassTwo>::ModuleType a; }
12345678910111213141516171819202122232425262728293031在上面代码中,一共有三处使用了using,分别是第3,16,22行,它们的作用为:
引入命名空间指定别名在子类中引用基类的成员引入命名空间
指定命名空间是C++ using namespace中最常被用到的地方,在第3行中的:
using namespace std; 1
指定别名
using的另一个作用是指定别名,一般都是using a = b;这样的形式出现,比如在13行中:
using ModuleType = ClassOne; 1
ModuleType 是ClassOne的一个别名。
using这个作用也比较常见,比如在vector.h中就有:
template<class _Ty,class _Alloc = allocator<_Ty>>class vector: public _Vector_alloc<_Vec_base_types<_Ty, _Alloc>> { public:using value_type = _Ty;using allocator_type = _Alloc; } 123456
即value_type 是_Ty的一个别名,value_type a; 和_Ty a;是同样的效果。
在子类中引用基类的成员
using的第三个作用是子类中引用基类的成员,一般都是using CBase::a;这样的形式出现,比如在22行中:
using typename ClassType::ModuleType; 1
它和一般形式有些区别,就是它加了个typename 修饰,这是因为类ClassThree本身是个模板类,它的基类ClassType是个模板,这个typename 和using其实没有什么关系。如果ClassType不是模板的话,这行代码就可以写成:
using ClassType::ModuleType; 1
剩下的就是using的作用,它引用了基类中的成员ModuleType, ModuleType又是类ClassOne的别名,所以后面ModuleType m;相当于定义对象m,对于子类成员m来说,这样的效果和下面是相同的:
typename ClassType::ModuleType m; 1
不同之处在于using还修改了基类成员的访问权限,子类ClassThree 私有继承ClassType,所以ClassType中共有成员ModuleType 在子类ClassThree 是私有的,它不能被外部访问。但是使用using后,在main()函数中可以使用。
相关知识
字符串 (C++/CX)
typename的历史及用法
小白初学C++的引用
c++学习
C++: 水仙花数
c++第二次实验
c++学习笔记(十六)typedef和using的可读性比较
C++中重载、重写(覆盖)的区别实例分析
CCF NOI1008. 水仙花数 (C++)
vld(Visual Leak Detector) 内存泄露检测工具,Visual C++ 2008
网址: C++ using用法 https://www.huajiangbk.com/newsview1141745.html
上一篇: Python图形界面设计(Tki |
下一篇: 【matlab】结构体 |
推荐分享

- 1君子兰什么品种最名贵 十大名 4012
- 2世界上最名贵的10种兰花图片 3364
- 3花圈挽联怎么写? 3286
- 4迷信说家里不能放假花 家里摆 1878
- 5香山红叶什么时候红 1493
- 6花的意思,花的解释,花的拼音 1210
- 7教师节送什么花最合适 1167
- 8勿忘我花图片 1103
- 9橄榄枝的象征意义 1093
- 10洛阳的市花 1039