我很想知道typedef究竟是如何工作的.
typedef struct example identifier;
identifier x;
Run Code Online (Sandbox Code Playgroud)
在上面的语句中,'identifier'只是在代码中用'struct example'替换(像字符串替换这样的东西)?如果不是,typedef在这做什么?
请指教!
Ama*_*osh 32
不,它不是字符串替换 - 这将是宏.它为该类型创建别名.
对于自定义类型,typedef优先于宏,部分原因是它们可以正确编码指针类型.
typedef char *String_t;
#define String_d char *
String_t s1, s2;
String_d s3, s4;
Run Code Online (Sandbox Code Playgroud)
s1,s2和s3都被声明为char*,但s4被声明为char,这可能不是意图.
A typedef引入了类型的同义词.它不是普通的字符串替换,如下所示:
typedef int* int_ptr;
const int* a; // pointer to const int
const int_ptr b; // const pointer to int
Run Code Online (Sandbox Code Playgroud)
编译器也知道它是一个类型名称,你不能只是把它放在一个不允许类型的地方而不会出现编译器错误.
所有人都同意,它不是类型替换,并且它比指针进入混合时要好得多,但也有其他细微之处.特别是使用typedef会影响代码的解析方式和程序的有效性.
在C和C++中,用户定义的标识符都保存在不同的名称空间中(不是在C++意义上,而是某种标识符空间).使用typedef关键字时,可以为全局名称空间中的类型创建别名,其中包含函数.
// C/C++
struct test {};
void test( struct test x ) {} // ok, no collision
// C/C++
typedef struct test {} test; // test is now both in types and global spaces
//void test() {} // compiler error: test is a typedef, cannot be redefined
Run Code Online (Sandbox Code Playgroud)
这里略有不同的是,在C++中,编译器将首先查看全局名称空间,如果没有找到它,它也会查看类型名称空间:
// C
struct test {};
//void f( test t ); // error, test is not defined in the global namespace
void f( struct test t ); // ok, we are telling the compiler where to look
// C++
struct test {};
void f( test t ); // ok, no test defined in the global name space,
// the compiler looks in the types name space
void g( struct test t ); // also ok, even if 'struct' not needed here.
Run Code Online (Sandbox Code Playgroud)
但这并不意味着合并了两个名称空间,只是查找将在两个位置进行搜索.