Luc*_*ore 79 c++ pointers const
根据我的理解,const
修饰符应该从右到左阅读.从那以后,我明白了:
const char*
Run Code Online (Sandbox Code Playgroud)
是一个指针,其char元素不能被修改,但指针本身可以,和
char const*
Run Code Online (Sandbox Code Playgroud)
是一个指向mutable
字符的常量指针.
但是我得到以下代码的以下错误:
const char* x = new char[20];
x = new char[30]; //this works, as expected
x[0] = 'a'; //gives an error as expected
char const* y = new char[20];
y = new char[20]; //this works, although the pointer should be const (right?)
y[0] = 'a'; //this doesn't although I expect it to work
Run Code Online (Sandbox Code Playgroud)
那么是哪一个呢?我的理解还是我的编译器(VS 2005)错了?
Gre*_*son 127
实际上,根据标准,const
直接将元素修改为左侧.const
在声明开头使用只是一个方便的心理捷径.所以以下两个陈述是等价的:
char const * pointerToConstantContent1;
const char * pointerToConstantContent2;
Run Code Online (Sandbox Code Playgroud)
为了确保指针本身不被修改,const
应该放在星号后面:
char * const constantPointerToMutableContent;
Run Code Online (Sandbox Code Playgroud)
要保护指针和指向的内容,请使用两个consts.
char const * const constantPointerToConstantContent;
Run Code Online (Sandbox Code Playgroud)
我个人采用总是将const放在我打算不修改的部分之后,即使指针是我希望保持不变的部分,我也保持一致性.
iam*_*ind 30
它的工作原因是两者都相同.可能你对此感到困惑,
const char* // both are same
char const*
Run Code Online (Sandbox Code Playgroud)
和
char* const // unmutable pointer to "char"
Run Code Online (Sandbox Code Playgroud)
和
const char* const // unmutable pointer to "const char"
Run Code Online (Sandbox Code Playgroud)
[要记住这一点,这是一个简单的规则,'*'首先影响其整个LHS ]
Aka*_*ksh 24
那是因为规则是:
规则:const
左边绑定,除非左边没有任何东西,然后绑定吧:)
所以,看看这些:
(const --->> char)*
(char <<--- const)*
Run Code Online (Sandbox Code Playgroud)
两者一样!哦,--->>
并且<<---
都没有的运营商,他们只是展示一下const
结合到.
Seb*_*ach 11
(来自2个简单变量初始化问题)
一个非常好的经验法则const
:
从右到左阅读声明.
(参见Vandevoorde/Josutiss"C++模板:完整指南")
例如:
int const x; // x is a constant int
const int x; // x is an int which is const
// easy. the rule becomes really useful in the following:
int const * const p; // p is const-pointer to const-int
int const &p; // p is a reference to const-int
int * const * p; // p is a pointer to const-pointer to int.
Run Code Online (Sandbox Code Playgroud)
自从我遵循这个经验法则之后,我再也没有误解过这样的声明.
(:sisab retcarahc-rep a no ton,sisab nekot-rep a tfel-ot-thgir naem I hguohT:tidE
以下是我总是试图解释的方式:
char *p
|_____ start from the asterisk. The above declaration is read as: "content of `p` is a `char`".
Run Code Online (Sandbox Code Playgroud)
char * const p
|_____ again start from the asterisk. "content of constant (since we have the `const`
modifier in the front) `p` is a `char`".
Run Code Online (Sandbox Code Playgroud)
char const *p
|_____ again start from the asterisk. "content of `p` is a constant `char`".
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!