age*_*217 7 c++ pointers reference
我是C++社区的新手,只是快速询问C++如何通过引用函数来传递变量.
如果要在C++中通过引用传递变量,可以&向要通过引用传递的任何参数添加一个.当你为一个被引用传递的变量赋值时为什么这么说variable = value;而不是说*variable = value?
void add_five_to_variable(int &value) {
// If passing by reference uses pointers,
// then why wouldn't you say *value += 5?
// Or does C++ do some behind the scene stuff here?
value += 5;
}
int main() {
int i = 1;
add_five_to_variable(i);
cout << i << endl; // i = 6
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果C++使用指针来实现幕后魔术,为什么不像指针一样需要解引用?任何见解都会非常感激.
写的时候
int *p = ...;
*p = 3;
Run Code Online (Sandbox Code Playgroud)
这是将3分配给指针引用的对象的语法p.写的时候
int &r = ...;
r = 3;
Run Code Online (Sandbox Code Playgroud)
这是将3分配给引用引用的对象的语法r.语法和实现是不同的.使用指针实现引用(除非它们被优化),但语法不同.
所以你可以说在必要时会自动解除引用.