使用C ++ Typedef/使用类型别名 [英] Using c++ typedef/using type alias

查看:60
本文介绍了使用C ++ Typedef/使用类型别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读C ++入门书,完全不懂一行:

I am reading C++ primer book and completely don't understand one line:

 using int_array = int[4]; 
 typedef int int_array[4]; // This line
 for (int_array *p = ia; p != ia + 3; ++p) {
      for (int *q = *p; q != *p + 4; ++q)
          cout << *q << ' '; cout << endl;
 }

确定 typedef using 相同.这是否意味着 int [4] [4] 现在是 int 以及如何理解?在 for 循环中, int_array 是什么类型?

Ok typedef is same as using. Does it mean int[4][4] is now int and how to understand that? And what type is int_array in for loop?

谢谢

推荐答案

TL; DR

两者都在做完全相同的事情:将 int_array 定义为4个 int s

使用具有很好的A = B表示法,通常更容易理解.

using has a nice A = B notation that is generally much easier to understand.

using alias = type;

typedef 的表示法不是很落后.对于一个简单的 typedef

typedef's notation is not quite backward. For a simple typedef

typedef type alias;

,但更复杂的 typedef 往往会蔓延.我怀疑语法是根据定义变量的方式建模的,但是我找不到我的旧K& R C编程书的副本,现在也找不到.

but more complicated typedefs tend to sprawl. I suspect the syntax was modeled after how one would define a variable, but I can't find where I packed my copy of the old K&R C programming book and can't look that up at the moment.

int int_array[4];

int_array 定义为4个 int 的数组.在前面拍拍 typedef

would define int_array to be an array of 4 ints. Slapping typedef on the front

typedef int int_array[4];

使 int_array 成为类型别名,而不是变量.

makes int_array a type alias instead of a variable.

另一个例子,

int * intp;

intp 定义为指向 int 的指针.

typedef int * intp;

intp 定义为 int 的类型指针的别名.

Defines intp to be an alias to the type pointer to an int.

使用更复杂的数据类型会变得很丑陋,因为 typedef 别名的名称可能埋在定义的中间.一个 typedef 函数指针,例如:

This gets ugly with more complicated data types as the name of the typedefed alias may be buried somewhere in the middle of the definition. A typedefed function pointer for example:

typedef void (*funcp)(param_t param1, param_t param2, ...);

使用

using funcp = void (*)(param_t param1, param_t param2, ...);

制作2D阵列

如果您想要2D阵列,可以

Making a 2D Array

If you want a 2D array you could

using int_array2D = int[4][4];

或者您可以定义一个int_array数组

or you could define an array of int_array

using int_array2D = int_array[4];

当然,这意味着您可以

using int_array3D = int_array2D[4];

继续前进,直到奶牛回家,或者您打包了很多东西,以致医生的大脑融化了.

and keep on going until the cows come home or you've packed on so many dimensions that The Doctor's brain melts.

这篇关于使用C ++ Typedef/使用类型别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆