ryf*_*059 8 c++ pointers const
我一直想知道什么是正确的位置*和&.似乎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);
Run Code Online (Sandbox Code Playgroud)
这些例子并非详尽无遗.我在声明或传递给函数时到处看到它们.他们甚至意味着同样的事情吗?但是我也看到了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
Run Code Online (Sandbox Code Playgroud)
所以我得出结论:
T const* p; // pointer to const T
const T* p // seems same from above
T* const p; // const pointer to T
Run Code Online (Sandbox Code Playgroud)
尽管如此,这让我感到很困惑.编译器不关心位置和它们所需的间距吗?
编辑:我想知道一般情况.如果是,在什么情况下.
Jer*_*fin 13
白色空间的重要性仅在于它使令牌不能一起运行(例如)创建单个令牌,因此(例如)int x明显不同于intx.
当你处理类似的东西时int const*x;,任何一个大小的空格对*编译器完全没有区别.
a pointer to const int和之间的区别const pointer to int取决于*const的哪一侧.
int const *x; // pointer to const int
int *const x; // const pointer to int
Run Code Online (Sandbox Code Playgroud)
当/如果在同一声明中定义/声明多个对象时,主要区别在于可读性.
int* x, y;
int *x, y;
Run Code Online (Sandbox Code Playgroud)
在第一个中,有人可能会认为x和y是指向int的指针 - 但实际上,x是指向int的指针,y是int.对某些人来说,第二个更准确地反映了这个事实.
防止任何误解的一种方法是一次只定义一个对象:
int *x;
int y;
Run Code Online (Sandbox Code Playgroud)
对于其中任何一个,如果你完全忽略空格,那么正确的解释是相当容易的(除了告诉你一个toke结束而另一个开始,所以你知道"const int"是两个标记)并从右到左阅读,读*作"指针"至".例如:int volatile * const x;被读为"x是指向volatile int的const指针".