mir*_*zma 4 c++ pointers reference
在说这将是一个重复的问题和downvote(之前发生过)之前,我搜索并发现没有任何相似之处.
我和许多其他人一样,正在尝试学习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
Run Code Online (Sandbox Code Playgroud)
该表希望反映所有合法传递的参数.
[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)
Run Code Online (Sandbox Code Playgroud)
一个功能
void foo(int& n);
Run Code Online (Sandbox Code Playgroud)
不接受地址(指针),也不接受文字.
所以你不能称之为
int a = ...;
foo(&a); // Trying to pass a pointer to a function not taking a pointer
Run Code Online (Sandbox Code Playgroud)
要么
foo(1); // Passing R-value is not allowed, you can't have a reference to a literal value
Run Code Online (Sandbox Code Playgroud)
但是有一个例外,如果你有一个恒定的引用,比如
int foo(const int& n);
Run Code Online (Sandbox Code Playgroud)
允许使用文字值,因为这样就无法更改引用的值.
同样地
void foo(int* n);
Run Code Online (Sandbox Code Playgroud)
你必须传递指针.
例如:
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
Run Code Online (Sandbox Code Playgroud)
最后一个:
void foo(int n);
Run Code Online (Sandbox Code Playgroud)
举例:
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
Run Code Online (Sandbox Code Playgroud)