为什么在使用typedef时将非const指针视为const? [英] Why is the non-const pointer being treated as a const when using typedef?
问题描述
typedef char* c;
const c ptr1 = "pointer";
++ptr1; /// error
const char* ptr2 = "pointer";
++ptr2; /// runs fine
现在ptr1
应该是const char*
类型,因此是非常量指针,那么为什么将其视为常量指针?
Now ptr1
should be of type const char*
and thus a non-const pointer, then why is it being treated as a constant pointer ?
推荐答案
它们不相同.
第一个表示一个指向const-char的指针,第二个表示一个指向const-char的指针.
The first designates a const-pointer-to-char, the second is a pointer-to-const-char.
尝试从右到左阅读:
const char *p; // p is a pointer to char which is const
char const *p; // p is a pointer to const char (same as previous)
char * const p; // p is a const pointer to char
char const * const p; // p is a const pointer to const char
通过使用typedef typedef char* c
,您将指向char的指针"的含义打包到单个别名c
中:
By using the typedef typedef char* c
you pack the meaning "pointer to char" into a single alias c
:
const c p; // p is a const [c] --> p is a const [pointer to char]
其他说明:
Typedef并不像宏那样就地扩展.
Typedefs are not in-place-expanded like macros are, i.e.
const c p;
真正成为
const [char*] p;
不是变成
const char* p; // Nope.
不要在您的脑海中像宏一样扩展它,使用typedef可以将char
和*
绑定在一起并形成一个原子.
Don't expand it like macros in your mind, with the typedefs, you've bound char
and *
together and formed an atom.
这篇关于为什么在使用typedef时将非const指针视为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!