C++11using用法

C++11中using关键字的主要作用是:为一个模板库定义一个别名。

下面列举出using的几种用法:

/*定义别名*/
 template<class T>
 using Tlist = std::list<T>;
 
 using Tlist = std::list<char>;
 Tlist listChar;
 
 //typedef void(*df)();
  using  df = void(*)();

/*使用外部构造*/
 using A::A;
 
/*引用外部类型*/
using typename A;

1、用法一:引用命名空间

using namespace std;

2、用法二:alias的使用
using 还可以指定别名,比如using SO3d = SO3<double>; 那么它和typedef ,有什么区别?

可读性
我们使用typedef定义函数指针:typedef void (* FUN_) (int, int); 函数指针指向的函数返回值是void,输入参数是int, int型。
我们使用using 定义函数指针:using FUN_ = void(*)(int, int);
using的写法把别名的名字强制分离到了左边,而把别名指向的放在了右边,比较清晰

此外,using可以指定模板的别名,而typedef不行

/*假如我们定义一个类模板:*/
template<class _scale, int option>
class Person
{
public:
    _scale age;
    _scale name[option];
};

template<class _T>
using myperson = Person<_T, 6>;  // Ok

//typedef Person<_T, 6> myperson; // fail

myperson<int> p;

3、用法三:子类引用基类成员
假如子类私有继承父类,子类无法使用父类的成员(变量,函数等),但是使用using可以访问,code如下:

template<class _scale, int option>
class Person
{
public:
    _scale age;
    _scale height;
    _scale name[option];

	void myprint(void)
	{
		cout << "age" << age << endl;
	}
};


template<class _scale, int option>
class HeighPerson : private Person<_scale, option>
{
public:
    using Person<_scale, option>::age; // 使用using 之后变成public
    using Person<_scale, option>::myprint; // 使用using, myprint之后变成public
    
protected:
	using Person<_scale, option>::height;  //在本来不可访问的,使用using 之后变成protected
    void test(void)
    {
	cout << "age" << age << endl;
    }
};

注:此时也只可通过using访问基类的public、protected成员,private成员依旧不可访问;

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Star星屹程序设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值