C++ typedef const 指针的解释

C++ typedef interpretation of const pointers(C++ typedef const 指针的解释)
本文介绍了C++ typedef const 指针的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

首先,示例代码:

案例 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 指针的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)