C++11新特性(5)- 类型别名

为什么需要别名


下面的说明只是一个例子,实际的使用场景一定不止这些。


假设有一个二维图形计算的程序,定义了一个point结构体。


struct point

{

   int x;

   int y;

};


在有些系统中,int类型的精度,范围都足够,在其他的系统中可能就不能满足需求,可能需要扩大字长,或者需要提高精度等等。


方法有多种,其中之一就是定义别名。在C++11中定义别名的方法如下:


using dtype = int;


它的含义是为int指定一个别名,dtype。指定别名以后,point结构体变成下面这样:


struct point

{

   dtype x;

   dtype y;

};


这样一来,只要改变dtype所对应的数据类型,所有使用point的代码都会适应这种变化。


下面说明另一种场景。继续假设这个程序中也会用到vector:


vector<point> v = {{1, 2}, {3, 4}};

vector<point>::iterator it = v.begin();

 while(it != v.end()){

       cout << (*it).x << "," << (*it).y << endl;

       it++;

 }


如果类似代码多次出现,每次输入相同的内容,有些人就会觉得麻烦。这时可以为vector<point>定义一个别名:


using PointVector = vector<point>;  //定义别名


PointVector va = {{1, 2}, {3, 4}};

PointVector::iterator ita = va.begin();

while(ita != va.end()){

       cout << (*ita).x << "," << (*ita).y << endl;

       ita++;

 }


定义别名,提供了另一种看程序的方式。


类型别名和typedef有什么区别?


typedef也能提相同的功能,但是形式略有不同。


typedef int dtype;    //等价于using dtype = int;

typedef vector<point> PointVector; //等价于using Point

typedef void(*PtoF)(int); //等价于using PtoF=void(*)(int);


C++11的别名定义方式似乎更容易理解一些。除此以外区别似乎不大,就看你怎么选了。
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】,轻松学习每一天!

以上就是今天的文章,欢迎点赞并推荐给您的朋友!

阅读更多更新文章,请扫描下面二维码,关注微信公众号【面向对象思考】

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/79822644
今日推荐