我看到了一些这样的 C 代码:
// A:
typedef uint32_t in_addr_t;
struct in_addr { in_addr_t s_addr; };
我总是喜欢这样:
// B:
typedef uint32_t in_addr;
所以我的问题是:在 A 和 B 中执行此操作有什么区别/好处?
最佳答案
这是一个引入类型安全的层,对“ future 的扩展”很有帮助。
前者的一个问题是,很容易将由 typedefed 内置表示的类型的值“转换”为几种其他类型或 typedefed 内置中的任何一种。
考虑:
typedef int t_millisecond;
typedef int t_second;
typedef int t_degrees;
对比:
// field notation could vary greatly here:
struct t_millisecond { int ms; };
struct t_second { int s; };
struct t_degrees { int f; };
在某些情况下,使用符号会更清晰一些,编译器也会禁止错误的转换。考虑:
int a = millsecond * second - degree;
这是一个可疑程序。使用类型定义的整数,这是一个有效的程序。使用结构时,它的格式不正确——编译器错误将需要您进行更正,并且您可以明确表达您的意图。
使用 typedef,可以应用任意算术和转换,并且可以在没有警告的情况下将它们分配给彼此,这可能成为维护的负担。
同时考虑:
t_second s = millisecond;
这也是一个致命的转变。
它只是工具箱中的另一个工具——请自行决定使用。
关于c - 只将一个基本字段封装到 C 中的结构中有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10409537/