C++ 类型别名

类型别名(type alias)

类型别名:

类型的另外一个标识符。

类型别名的用途:

可以使复杂的类型标志变得简短明了、更易于理解和使用,有助于程序员清楚的直到使用该类型的真实目的。

有两种方法可以用于定义类型别名:

  • 传统方法使用关键字 typedef
  • C++新标准规定了一种新方法,使用关键字 using 进行 别名申明(alias declaration)来定义类型的别名。
  • 从使用语法来看 using 比 typedef 更加简洁明了,推荐使用 using 关键字进行别名定义

typedef 类型定义

1 // 关键字 typedef
2   typedef string t1, *t2, &t3;
3   t1 name_one = "Lili";      // t1 与 string 同义
4   t2 name_two = &name_one;   // t2 与 string* 同义
5   t3 name_three = name_one;  // t3 与 string& 同义 
6   cout << name_one << endl << *name_two << endl << name_three;

using 别名申明

1 // 关键字 using
2   using t1 = string;
3   using t2 = t1*;
4   using t3 = string&;
5   t1 name_one = "Lili";      // t1 与 string 同义
6   t2 name_two = &name_one;   // t2 与 string* 同义
7   t3 name_three = name_one;  // t3 与 string& 同义 
8   cout << name_one << endl << *name_two << endl << name_three;

猜你喜欢

转载自www.cnblogs.com/Yu-900914/p/10036107.html
今日推荐