gpt4 book ai didi

c++ - 我正在尝试将 C++ 引用与指针相关联

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:52 25 4
gpt4 key购买 nike

在说这将是一个重复的问题和否决票(就像以前发生的那样)之前,我进行了搜索,但没有发现任何相似的东西。
我和许多其他人一样,正在尝试学习 C++ 引用变量的使用并将它们与指针相关联。我发现制作表格更容易,我需要知道它是否需要修改。

                   int *n   int n    int &n    caller/local
void foo(int *n) n &n &n caller
void foo(int n) *n n n local
void foo(int &n) *n n n caller

表格要反射(reflect)所有合法传递的参数。

[1,1]: passing by reference (trivial)  
[1,2]: passing by reference
[1,3(1)]: passing by reference, an is an address(?)
[1,3(2)]: passing by reference, as n is used as alias(?)
[2,1]: passing by value, as dereferencing
[2,2]: passing by value (trivial)
[2,3(1)]: passing by value, using value of n (where n is an alias)
[2,3(2)]: passing by value (dereferencing n, which is an address)
[3,1(1)]: passing by reference, as foo accepts address
[3,1(2)]: passing by reference, reference of value at address n
[3,2(1)]: passing by reference (trivial)
[3,2(2)]: passing by reference, as foo accepts address or reference
[3,3]: passing by reference (trivial, as argument matches parameter exactly)
  1. 表格和解释是否正确?
  2. 表中是否遗漏了任何情况(派生的情况除外,如 *&n、指向指针的指针等)?

最佳答案

一个函数

void foo(int& n);

接受地址(指针),也不接受文字。

所以你不能这样调用它

int a = ...;
foo(&a); // Trying to pass a pointer to a function not taking a pointer

foo(1);  // Passing R-value is not allowed, you can't have a reference to a literal value

但是有一个异常(exception),如果你有一个常量引用,比如

int foo(const int& n);

然后允许使用文字值,因为这样引用的值就不能更改。


同样适用于

void foo(int* n);

必须传递一个指针。

例如:

int a = ...;
int& ra = a; // ra references a

foo(&a); // OK
foo(&ra); // OK
foo(a); // Fail, a is not a pointer
foo(ra); // Fail, ra is not a pointer
foo(1); // Fail, the literal 1 is not a pointer

最后:

void foo(int n);

举例说明:

int a = ...;
int& ra = a; // ra references a
int* pa = &a; // pa points to a

foo(a); // OK, the value of a is copied
foo(ra); // OK, the value of the referenced variable is copied
foo(*pa); // OK, dereferences the pointer, and the value is copied
foo(pa); // Fail, passing a pointer to a function not expecting a pointer
foo(1); // OK, the literal value 1 is copied

关于c++ - 我正在尝试将 C++ 引用与指针相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24450463/

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