为什么要更改这两个代码输出的“&”字符?
Why changes the '&' character the output for these two codes?
第一个密码:
int a = 1;
void func(int* ptr) {
ptr = &a;
}
int main() {
int nvar = 2;
int* pvar = &nvar;
func(pvar);
std::cout << *pvar;
}
//Output: 2
第二个密码:
int a = 1;
void func(int*& ptr) {
ptr = &a;
}
int main() {
int nvar = 2;
int* pvar = &nvar;
func(pvar);
std::cout << *pvar;
}
//Output: 1
唯一的区别是 'func' 函数中的 '&' 字符。但是谁能解释一下,在这种情况下它是做什么的?
I know what it does, but in the second code it is combined with * , and I dont know what this combination means
T&
表示"reference to T
"。
现在将 T
替换为您喜欢的任何内容。例如,对于指向 int
、T==int*
的指针,我们有 int*&
这是对指向 int
.
的指针的引用
这与将非指针作为引用传递给函数没有什么不同。当 ptr
按值传递时, func
在副本上工作,当按引用传递时 func
在传入的实例上工作。
The difference between pass-by-reference and pass-by-value is that modifications made to arguments passed in by reference in the called function have effect in the calling function, whereas modifications made to arguments passed in by value in the called function can not affect the calling function. Use pass-by-reference if you want to modify the argument value in the calling function. Otherwise, use pass-by-value to pass arguments.
我认为这比我能说的更好。
第一个密码:
int a = 1;
void func(int* ptr) {
ptr = &a;
}
int main() {
int nvar = 2;
int* pvar = &nvar;
func(pvar);
std::cout << *pvar;
}
//Output: 2
第二个密码:
int a = 1;
void func(int*& ptr) {
ptr = &a;
}
int main() {
int nvar = 2;
int* pvar = &nvar;
func(pvar);
std::cout << *pvar;
}
//Output: 1
唯一的区别是 'func' 函数中的 '&' 字符。但是谁能解释一下,在这种情况下它是做什么的?
I know what it does, but in the second code it is combined with * , and I dont know what this combination means
T&
表示"reference to T
"。
现在将 T
替换为您喜欢的任何内容。例如,对于指向 int
、T==int*
的指针,我们有 int*&
这是对指向 int
.
这与将非指针作为引用传递给函数没有什么不同。当 ptr
按值传递时, func
在副本上工作,当按引用传递时 func
在传入的实例上工作。
The difference between pass-by-reference and pass-by-value is that modifications made to arguments passed in by reference in the called function have effect in the calling function, whereas modifications made to arguments passed in by value in the called function can not affect the calling function. Use pass-by-reference if you want to modify the argument value in the calling function. Otherwise, use pass-by-value to pass arguments.
我认为这比我能说的更好。