gpt4 book ai didi

c++ - 为什么可以只给一个接受引用的函数一个对象(而不是一个引用)?是否自动生成引用?

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

例如:

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.
}

为什么 do_something(x) 有效?它没有提供函数所要求的功能。我能想到的唯一解释是传递给函数的 int 有一个为它创建的引用,而该引用最终被传递给函数。

最佳答案

查看引用的一种方法是将其视为别名。它只是现有对象的新名称,您可以使用现有名称或您为其指定的新名称。这意味着

void do_something(int& x)

并不真的需要传递给它的引用。它的意思是 x 将是对某个 int 对象的引用。以这种方式看待它,您可以将 int 传递给 do_something 是完全合理的,因为您正在为它提供 x 的 int 将引用。

反之亦然。如果你有

void do_something(int x)

您仍然可以将 y 传递给它,因为 y 只是 int 的名称。

关于c++ - 为什么可以只给一个接受引用的函数一个对象(而不是一个引用)?是否自动生成引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56278719/

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