函数声明的返回类型中的&符号如何工作? [英] How does ampersand in the return type of a function declaration work?

查看:178
本文介绍了函数声明的返回类型中的&符号如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,为什么f()被声明为double& f(...)是什么意思,它是如何工作的?我甚至不知道如何找到答案

  double a = 1,b = 2; 
double& f(double & d){
d = 4;
返回b;
}

我知道符号符号意味着变量或函数的地址,但我不明白为什么在声明函数时写出它是有意义的。

解决方案

当在声明表单中使用& 操作符时,在类型前面并不表示地址的引用,它本质上是一个自动解除引用的指针,禁止指针运算。

在C中没有引用,所以如果你想传递或返回通过引用,您必须传递一个const指针并将其解引用以访问指向的值使这个概念变得更容易,以防止意外地通过指针算术走出地址,并且保存解引用指针的需要。这使得使用它变得更容易,并且产生更清晰和更易读的语法。


In this piece of code, why f() is declared as "double & f(..."? What does it mean and how does it work? I don't even know what to google to find the answer to my question. Please help.

double a = 1, b = 2;
double & f (double & d) {
    d = 4;
    return b;
}

I know ampersand sign means the address of a variable or a function, but I don't see why it would make sense to write it when you are declaring a function.

解决方案

When the & operator is used in a declaration form, preceded by a type it doesn't mean "the address of" but a "reference to" which is essentially an automatically dereferenced pointer with disabled pointer arithmetic.

There are no references in C, so if you want to pass or return by reference, you had to pass a const pointer and dereference it to access the pointed to value. C++ added references to make this concept easier, to prevent accidental walking off the address with pointer arithmetic, and to save the need to dereference the pointer. This makes working with it much easier and resulting in cleaner and more readable syntax.

这篇关于函数声明的返回类型中的&符号如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆