【发布时间】:2024-01-14 18:44:01
【问题描述】:
可能重复:
Declaring pointers; asterisk on the left or right of the space between the type and name?
我一直想知道将* 和& 放在什么位置才是正确的。似乎 C++ 对放置这些标记的位置非常宽容。
例如,我似乎将指针和 & 号放在关键字的左右两侧或两个关键字的中间,但令人困惑的是,有时它们似乎意味着相同的东西,尤其是与 const 一起使用时@
void f1(structure_type const& parameter)
void f2(structure_type const ¶meter)
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
不过,这让我很困惑。编译器不关心它们所需的位置和间距吗?
编辑: 我想大致了解职位的重要性。如果是,在什么情况下。
【问题讨论】:
-
这似乎意味着指针本身是常量 -- ideone.com/okePlO
-
只是不要使用多个指针级别,否则你的头会爆炸:
int const**const*const*const****const** wtf;Technically legal, but insane. -
@chris this link 说它指向一个常量字段。但无论如何, const 的顺序可以改变的事实已经让我很困惑了。
-
@ryf9059, Read this。它工作得很好,但在这种情况下,从右到左阅读就足够了。