为什么 C++ 被设计成在同一行声明两个 int *s 的正确方法是
int *x, *y;
不是
int* x,y;
我知道有些人认为您应该避免使用任何一种形式并在单独的行中声明每个变量,但我对为什么做出这种语言决定很感兴趣。
最佳答案
为了保持与 C 代码的兼容性,因为 C 就是这样工作的。
Bjarne 提出了一个很好的观点 in his style and technique faq :
The choice between
int* p;
andint *p;
is not about right and wrong, but about style and emphasis. C emphasized expressions; declarations were often considered little more than a necessary evil. C++, on the other hand, has a heavy emphasis on types.A typical C programmer writes
int *p;
and explains it*p is what is the int
emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.A
typical C++ programmer
writesint* p;
and explains itp is a pointer to an int
emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.
因此,在 C++ 中像 this 这样工作的动机是它在 C 中的工作方式。
它在 C 中工作的动机是,如上所述,C 强调表达式而不是类型。
关于c++ - 为什么 c++ 指针 * 关联到声明的变量,而不是类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032802/