typedef
说明符
-
typedef
- 创建一个别名,该别名可以在任何地方替代(可能复杂的)类型名称。
-
目录 |
[编辑] 解释
当 typedef 说明符在声明中使用时,它指定该声明是一个 *typedef 声明*,而不是一个变量或函数声明。
通常,typedef 说明符出现在声明的开头,但也允许出现在类型说明符之后,或两个类型说明符之间。typedef 说明符不能与除类型说明符之外的任何其他说明符组合使用。
一个 typedef 声明可以在同一行声明一个或多个标识符(例如 int 和指向 int 的指针),它可以声明数组和函数类型、指针和引用、类类型等。在此声明中引入的每个标识符都成为一个 *typedef 名称*,它是如果删除关键字 typedef,它将成为的对象或函数的类型的同义词。
typedef 名称是现有类型的别名,而不是新类型的声明。typedef 不能用于更改现有类型名称(包括 typedef 名称)的含义。一旦声明,一个 typedef 名称只能被重新声明以再次引用相同的类型。Typedef 名称只在其可见的作用域中有效:不同的函数或类声明可以定义具有不同含义的同名类型。
typedef 说明符不能出现在函数参数的声明中,也不能出现在函数定义的 decl-specifier-seq 中。
void f1(typedef int param); // ill-formed typedef int f2() {} // ill-formed
typedef 说明符不能出现在不包含声明符的声明中。
typedef struct X {}; // ill-formed
[编辑] 用于链接目的的 typedef 名称
如果一个 typedef 声明定义了一个未命名的类或枚举,则该声明所声明的类类型或枚举类型的第一个 typedef 名称是该类型的 *用于链接目的的 typedef 名称*。
例如,在 typedef struct { /* ... */ } S; 中,S
是一个用于链接目的的 typedef 名称。以这种方式定义的类或枚举类型具有外部链接(除非它位于未命名空间中)。
以这种方式定义的未命名类应该只包含 C 兼容的构造。特别地,它不能
并且所有成员类也必须满足这些要求(递归地)。 |
(C++20 起) |
[编辑] 注意
类型别名提供与 typedef 声明相同的功能,但使用不同的语法,也适用于模板名称。 |
(C++11 起) |
[编辑] 关键词
[编辑] 示例
// simple typedef typedef unsigned long ulong; // the following two objects have the same type unsigned long l1; ulong l2; // more complicated typedef typedef int int_t, *intp_t, (&fp)(int, ulong), arr_t[10]; // the following two objects have the same type int a1[10]; arr_t a2; // beware: the following two objects do not have the same type const intp_t p1 = 0; // int *const p1 = 0 const int *p2; // common C idiom to avoid having to write "struct S" typedef struct { int a; int b; } S, *pS; // the following two objects have the same type pS ps1; S* ps2; // error: storage-class-specifier cannot appear in a typedef declaration // typedef static unsigned int uint; // typedef can be used anywhere in the decl-specifier-seq long unsigned typedef int long ullong; // more conventionally spelled "typedef unsigned long long int ullong;" // std::add_const, like many other metafunctions, use member typedefs template<class T> struct add_const { typedef const T type; }; typedef struct Node { struct listNode* next; // declares a new (incomplete) struct type named listNode } listNode; // error: conflicts with the previously declared struct name // C++20 error: "struct with typedef name for linkage" has member functions typedef struct { void f() {} } C_Incompatible;
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
CWG 576 | C++98 | typedef 不允许在整个函数定义中 | 在函数体中允许 |
CWG 2071 | C++98 | typedef 可以出现在不包含声明符的声明中 | 现在不允许 |
[编辑] 另请参阅
C 文档 关于 Typedef declaration
|