C++ typedef interpretation of const pointers(const 指针的 C++ typedef 解释)
问题描述
首先,示例代码:
案例一:
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
行为是没有意义的.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.
这篇关于const 指针的 C++ typedef 解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const 指针的 C++ typedef 解释
基础教程推荐
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01