例如:
void do_something(int& x){
//this function asks for a reference to an int,
//since the type of its argument is int&
}
int main() {
int x = 4; //the variable x is simply an int; it isn't a reference?
int& y = x; //the variable y is a reference to x
do_something(y); //this works, as expected
do_something(x);
//this calls the method with an int, instead of a reference.
//Why does this work? It's not giving the function what the function is
//asking for.
}
Run Code Online (Sandbox Code Playgroud)
为什么do_something(x)起作用?它没有提供该功能所需的功能。我能提出的唯一解释是,传递给函数的int有为其创建的引用,而引用最终就是传递给函数的。
查看参考的一种方法是将其视为别名。它只是现有对象的新名称,您可以使用现有名称或您为其赋予的新名称。那意味着
void do_something(int& x)
Run Code Online (Sandbox Code Playgroud)
并不需要传递给它的引用。它的意思是x将引用某个int对象。看它这样,它非常有意义,你可以传递一个int来do_something,因为你给它的int是x将引用。
反之亦然。如果你有
void do_something(int x)
Run Code Online (Sandbox Code Playgroud)
您仍然可以传递y给它,因为y它只是一个名称int。
如果一个引用只能绑定到其他引用,则将无法引用一个对象。
do_something(x)的工作原理相同int& y = x。在这两种情况下,参考变量都绑定到对象。对于函数调用,参考变量是一个参数。
我能想到的唯一解释是,传递给函数的int有为其创建的引用
“创建”所有功能参数-更通常是所有变量(功能参数本质上是局部变量)(尽管它取决于“创建”的含义)。如果变量是引用,则创建引用。如果变量不是引用,则创建一个对象。