在C++中,指针和带有常量的与号位置

pointer and ampersand position with const in C++

本文关键字:常量 位置 C++ 指针      更新时间:2023-10-16

可能重复:
声明指针;星号在类型和名称之间的空格的左边还是右边?

我一直想知道*&的确切正确位置是什么。C++似乎对把这些标记放在哪里很宽容。例如,我似乎在一个关键字的左右两侧或两个关键字的中间都放置了指针和符号,但有时令人困惑的是,它们似乎意味着相同的东西,尤其是当与const 一起使用时

void f1(structure_type const& parameter)
void f2(structure_type const &parameter)
void f2(structure_type  const *sptr);
void f2(structure_type  const* sptr);
void f2(structure_type  const * sptr);

这些例子并不详尽。当它们被声明或传递给函数时,我可以在任何地方看到它们。他们的意思是一样的吗?但我也看到了放置*会影响哪个对象被称为指针的情况(可能是*位于两个关键字之间的情况(。

编辑:

int const *Constant
int const * Constant // this above two seem the same to me, both as pointer to a constant value
int const* Constant //  EDIT: this one seems the same as above. instead of a constant pointer
const int * Constant // this is also a pointer to a constant value, but the word order changed while the pointer position stays the same, rather confusing.
int* const Constant
int * const Constant // instead, these two are constant pointers

所以我得出结论:

T const* p; // pointer to const T
const T* p  // seems same from above
T* const p; // const pointer to T

尽管如此,这还是让我很困惑。编译器不在乎它们的位置和间距吗?

编辑:我想知道职位的总体情况。如果是,在什么情况下。

空白仅在一定程度上重要,因为它阻止令牌一起运行和(例如(创建单个令牌,因此(例如(int xintx明显不同。

当您处理类似于:int const*x;的东西时,*的任意大小上的空白对编译器来说都没有任何区别。

pointer to const intconst pointer to int之间的差异取决于常量位于*的哪一侧。

int const *x;    // pointer to const int
int *const x;    // const pointer to int

当/如果在同一声明中定义/声明多个对象时,主要区别在于可读性。

int* x, y;
int *x, y;

在第一个例子中,有人可能认为x和y是指向int的指针,但事实上,x是指向int,y是int。在一些人看来,第二个例子更准确地反映了这一事实。

防止任何误解的一种方法是一次只定义一个对象:

int *x;
int y;

对于其中的任何一个,如果您完全忽略空白(除了告诉您一个标记在哪里结束,另一个标记从哪里开始,所以您知道"const int"是两个标记(,并从右向左读取,将*读取为"pointer to",那么正确的解释是相当容易的。例如:int volatile * const x;读作"x是指向volatile int的常量指针"。

int const *Constant
int const * Constant 
int const* Constant

以上所有内容都旨在声明一个指向常量整数的非常量指针。

简单规则:

如果const紧跟在*之后,则它应用于指针,否则它应用于指向的对象。间距无关紧要

两者&和*变量声明中的位置是可以接受的,并且只取决于您自己的口味。它们严格意义相同,分别创建一个指针和一个引用。

然而,const关键字的位置是原始的,因为int const* variable声明了一个指向非常量int的常量量的指针。