C++ using用法

31 篇文章 10 订阅
#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;
}

在上面代码中,一共有三处使用了using,分别是第3,16,22行,它们的作用为:

  • 引入命名空间
  • 指定别名
  • 在子类中引用基类的成员

引入命名空间

指定命名空间是C++ using namespace中最常被用到的地方,在第3行中的:

using namespace std;

指定别名

using的另一个作用是指定别名,一般都是using a = b;这样的形式出现,比如在13行中:

using ModuleType = ClassOne;

ModuleTypeClassOne的一个别名。
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;
}

value_type_Ty的一个别名,value_type a;_Ty a;是同样的效果。

在子类中引用基类的成员

using的第三个作用是子类中引用基类的成员,一般都是using CBase::a;这样的形式出现,比如在22行中:

using typename ClassType::ModuleType;

它和一般形式有些区别,就是它加了个typename 修饰,这是因为类ClassThree本身是个模板类,它的基类ClassType是个模板,这个typenameusing其实没有什么关系。如果ClassType不是模板的话,这行代码就可以写成:

using ClassType::ModuleType;

剩下的就是using的作用,它引用了基类中的成员ModuleTypeModuleType又是类ClassOne的别名,所以后面ModuleType m;相当于定义对象m,对于子类成员m来说,这样的效果和下面是相同的:

typename ClassType::ModuleType m;

不同之处在于using还修改了基类成员的访问权限,子类ClassThree 私有继承ClassType,所以ClassType中共有成员ModuleType 在子类ClassThree 是私有的,它不能被外部访问。但是使用using后,在main()函数中可以使用。

  • 54
    点赞
  • 103
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值