C / C ++中的typedef是否真的通过组合复合类型(例如int *)来创建NEW类型? [英] Does typedef in C/C++ really create a NEW type by combining the compound type (e.g. int*)?
问题描述
最近,我发现代码中的 typedef
的工作原理与我提出的完全不同。像这样的示例:
recently I found typedef
in my code works really different than what I proposed. An example like this:
typedef int *ptype;
ptype v1 = 0, v2 = 0;
结果:v1和v2均被定义为指向 int
类型。但是,如果您在第二句中将 ptype
替换为 int *
,则为 int * v1 = 0,v2 = 0;
或 int * v1 = 0,v2 = 0;
,只有v1将是指针,而v2是正常的 int
。看来 typedef
并不能做简单的替换。更重要的是,使修饰符复杂化,例如:
The result: both v1 and v2 were defined as a pointer to int
type. But if you simply replace ptype
by int *
in the second sentence as int *v1 = 0, v2 = 0;
or int* v1 = 0, v2 =0;
, only v1 will be the pointer and v2 is normal int
. It seems typedef
does not do a simple replacement. What's more, when it comes to complicate modifier like:
typedef int *ptype;
const ptype v3 = 0;
结果将是:v3是 const
指针,而不是指向 const
int的指针,如果我们编写 const int * v3 = 0;
。在上面的代码中, const
是整个 ptype
而不是 int <的修饰符。 / code>位于
ptype
中。因此,看起来真的像 typedef
组合了复合类型 int *
并创建了一个新类型。
The result will be: v3 is a const
pointer, not a pointer to the const
int if we write const int *v3 = 0;
. In the above code const
stands as the modifier to the whole ptype
, not the int
inside ptype
. Thus it really looks like typedef
combines the compound type int*
and creates a new type.
但是,权威的C / C ++参考网站 cplusplus 说 typedef不会创建不同的类型。它只会创建现有类型的同义词。所以我真的很困惑,希望有人可以帮助解释 typedef
的行为。谢谢!
However, the authoritative C/C++ reference website cplusplus says "typedef does not create different types. It only creates synonyms of existing types." so I was really confused and hope someone can help explain the behavior of typedef
. Thanks!
推荐答案
同义词并不表示文本替换。 ptype
并没有被预处理器或任何东西扩展为 int *
。
"Synonym" does not mean "text replacement". ptype
is not literally expanded to int *
by the preprocessor or anything.
这意味着您可以执行以下操作:
What it means is that you can do things like:
typedef int *ptype;
ptype a;
int *b;
a = b; // OK
该分配有效,因为 ptype
和 int *
是同一类型;
The assignment is valid because ptype
and int *
are the same type; there is no type conversion or cast required.
typedef
只是让您为现有类型命名。但是该名称将现有类型的各个方面组合成一个不可分割的实体,例如 ptype a,b;
等同于 ptype a; ptype b;
(和 const ptype
的意思是 const指向int的指针,因为 ptype
表示指向int的指针。
typedef
simply lets you give a new name to an existing type. But that name combines every aspect of the existing type into an indivisible entity, such that e.g. ptype a, b;
is equivalent to ptype a; ptype b;
(and const ptype
means "const pointer-to-int" because ptype
means "pointer-to-int").
换句话说,由 typedef <创建的新名称 / code>的行为就像内置关键字一样,但声明这些名称表示的实际类型相同。
In other words, the new names created by typedef
behave like built-in keywords as far as declaring things goes, but the actual types represented by those names are the same.
这篇关于C / C ++中的typedef是否真的通过组合复合类型(例如int *)来创建NEW类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!