gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:03 29 4
gpt4 key购买 nike

我是 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com