在C++中,指针和带有常量的与号位置
pointer and ampersand position with const in C++
可能重复:
声明指针;星号在类型和名称之间的空格的左边还是右边?
我一直想知道*
和&
的确切正确位置是什么。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
尽管如此,这还是让我很困惑。编译器不在乎它们的位置和间距吗?
编辑:我想知道职位的总体情况。如果是,在什么情况下。
空白仅在一定程度上重要,因为它阻止令牌一起运行和(例如(创建单个令牌,因此(例如(int x
与intx
明显不同。
当您处理类似于:int const*x;
的东西时,*
的任意大小上的空白对编译器来说都没有任何区别。
pointer to const int
和const 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的常量量的指针。
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 将值指定给向量(2D)的向量中的某个位置
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 非常量变量只读位置的赋值
- 常量引用的内存位置
- 当原始数据是常量时,修改指针指向的位置是 UB 吗?
- 非常量调用 const 成员函数失败,只读位置C++
- 指针或参照的常量位置
- 将强制转换为较窄的常量位置时是否暗示到常量?
- 使用新的位置来创建静态常量指针,指向静态内存缓冲区
- 测试静态常量成员的存储位置
- C++:I用不同的位置调用字符串 substr 两次,转换为常量字符 *,它们返回相同的,为什么
- 初始化 SSE 常量的位置
- 在c++类+ final常量中放置struct和enum的位置
- 编写JIT编译器时存储代码常量的位置
- 为什么迭代器向量::插入在填充后无效:迭代器插入(const_iterator位置,size_type n,常量value_type和val);
- 在C++中,指针和带有常量的与号位置
- 参数传递中常量位置的 c++ 标准是什么?