c++ - 为什么我们在定义指针时使用 "type * var"而不是 "type & var"?

标签 c++ syntax

我是 C++ 的新手(断断续续有大约一年的经验)。我很好奇是什么导致决定将 type * name 作为定义指针的语法。在我看来,语法应该是 type & name 因为 & 符号在代码中的其他任何地方都使用来引用变量的内存地址。因此,使用 int 指针的传统示例:

int a = 1;
int * b = &a;

会变成

int a = 1;
int & b = &a

我确信这其中有一些我没有看到的原因,我很想听听 C++ 老手的一些意见。

谢谢, -S

最佳答案

C++采用了C语法。正如“The Development of the C Language”(Dennis Ritchie 着)中所揭示的那样,C 在类型声明中使用 * 作为指针,因为它决定类型语法应该遵循 use。

For each object of [a compound type], there was already a way to mention the underlying object: index the array, call the function, use the indirection operator [*] on the pointer. Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear. Thus,

int i, *pi, **ppi;

declare an integer, a pointer to an integer, a pointer to a pointer to an integer. The syntax of these declarations reflects the observation that i, *pi, and **ppi all yield an int type when used in an expression.

这是一个更复杂的例子:

int *(*foo)[4][];

此声明意味着表达式 *(*foo)[4][0] 具有类型 int,并且从那个(和那个 [] 比一元 * 具有更高的优先级)您可以解码类型:foo 是指向 int 指针数组的大小为 4 的数组的指针。

这种语法在 C++ 中被采用是为了与 C 兼容。另外,不要忘记 C++ 在声明中使用 for &。

int & b = a;

上面一行表示一个引用变量引用了另一个int类型的变量。引用和指针的区别大致在于,引用只是初始化,你不能改变它们指向的位置,最后它们总是自动解引用。

int x = 5, y = 10;
int& r = x;

int sum = r + y; // you do not need to say '*r' automatically dereferenced.

r = y; // WRONG, 'r' can only have one thing pointing at during its life, only at its infancy ;)

关于c++ - 为什么我们在定义指针时使用 "type * var"而不是 "type & var"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1061387/

相关文章:

c++ - 如何应用 C++ 的 ReSharper Ultimate 命名样式

javascript - 为什么++[[]][+[]]+[+[]] 返回字符串 "10"?

c# - 在 C# 中测试泛型类型的惯用方法

scala - 参数 : _* mean in Scala? 是什么意思

sql - 将对象插入 SQL Server 中的 JSON 数组

c++ - 我们声明结构的两种方式有什么区别?

c++ - BSP 和 MPI 有什么区别?

c++ - 链接 CMakeLists : ld cannot find library

C++ 错误 : qualifiers can only be specified

c++ - 全局函数和不明确的参数 NULL 与 char* 在 vs 2013 和 GCC 之间