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
|