8

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

我一直想知道放置*and的确切正确位置是什么&。似乎 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);

这些例子并不详尽。在声明或传递给函数时,我到处都能看到它们。他们甚至是同一个意思吗?但是我也看到 put*会影响哪个对象被称为指针的情况(可能*是在两个关键字之间的情况)。

编辑:

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

尽管如此,这还是把我弄糊涂了。编译器不关心它们所需的位置和间距吗?

编辑:我想大致了解职位的重要性。如果是,在什么情况下。

4

3 回答 3

14

空白仅在它阻止令牌一起运行和(例如)创建单个令牌的程度上很重要,因此(例如)int x明显不同于intx.

当您处理类似:int const*x;的内容时,任何大小的空格对*编译器都没有任何影响。

pointer to const inta和之间的区别const pointer to int取决于*const 在哪一侧。

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”是两个令牌)并从右到左阅读,阅读*为“指针” ,正确的解释是相当容易的到”。例如:int volatile * const x;读作“x 是指向 volatile int 的 const 指针”。

于 2013-01-09T04:09:33.673 回答
3
int const *Constant
int const * Constant 
int const* Constant

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

简单的规则:

如果const紧随其后,*则适用于指针,否则适用于指向的对象。间距无所谓。

于 2013-01-09T04:06:18.027 回答
-3

变量声明中的 & 和 * 位置都是可接受的,仅取决于您自己的风格。它们严格意义上的意思是一样的,分别创建一个指针和一个引用。

但是,const 关键字的放置是原始的,因为 aint const* variable声明了一个指向非常量int 的常量指针,并且是一个指向常量int 的非常量指针。const int* variable

于 2013-01-09T04:08:46.510 回答