命名空间
变体
操作

typedef 说明符

来自 cppreference.cn
< cpp‎ | language
 
 
C++ 语言
 
 
  • 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 起)

[编辑] 关键字

typedef

[编辑] 示例

// 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++ 标准。

DR 应用于 已发布行为 正确行为
CWG 576 C++98 typedef 在整个函数定义中是不允许的 允许在函数体中
CWG 2071 C++98 typedef 可以出现在不包含声明符的声明中 现在不允许

[编辑] 参见

C 文档 for Typedef 声明