問題描述
首先,示例代碼:
案例 1:
typedef char* CHARS;
typedef CHARS const CPTR; // constant pointer to chars
文字替換CHARS變成:
Textually replacing CHARS becomes:
typedef char* const CPTR; // still a constant pointer to chars
情況 2:
typedef char* CHARS;
typedef const CHARS CPTR; // constant pointer to chars
文字替換CHARS變成:
Textually replacing CHARS becomes:
typedef const char* CPTR; // pointer to constant chars
在情況 2 中,在文本替換 CHARS 后,typedef 的含義發生了變化.為什么會這樣?C++ 如何解釋這個定義?
In case 2, after textually replacing CHARS, the meaning of the typedef changed. Why is this so? How does C++ interpret this definition?
推薦答案
在文本替換的基礎上分析 typedef
行為是沒有意義的.類型定義名稱不是宏,它們不會被文本替換.
There's no point in analyzing typedef
behavior on the basis of textual replacement. Typedef-names are not macros, they are not replaced textually.
正如你自己所說的
typedef CHARS const CPTR;
和
typedef const CHARS CPTR;
這是因為同樣的原因
typedef const int CI;
具有相同的含義
typedef int const CI;
Typedef-name 不定義新類型(僅是現有類型的別名),但它們在某種意義上是原子的",任何限定符(如 const
)都適用于最頂層,即它們適用于隱藏在 typedef-name 后面的整個類型.一旦你定義了一個 typedef-name,你就不能在其中注入"一個限定符來修改任何更深層次的類型.
Typedef-name don't define new types (only aliases to existing ones), but they are "atomic" in a sense that any qualifiers (like const
) apply at the very top level, i.e. they apply to the entire type hidden behind the typedef-name. Once you defined a typedef-name, you can't "inject" a qualifier into it so that it would modify any deeper levels of the type.
這篇關于C++ typedef const 指針的解釋的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!