使用“&” C ++中函数名称之前的运算符 [英] Use of '&' operator before a function name in C++
问题描述
参考定义对象的备用名称。引用类型引用
是另一种类型。我们通过编写形式为& d
,
的声明符来定义引用类型,其中 d
是
A reference defines an alternative name for an object. A reference type "refers to"
another type. We define a reference type by writing a declarator of the form &d
,
where d
is the name being declared.
接下来的事情是引用不是对象。相反,引用只是已经存在的对象的另一个名称。因此,我们将使用这些引用逐个传递参数,以便直接影响实际参数。
The next thing is a reference is not an object. Instead, a reference is just another name for an already existing object. So we'll use these references to pass the parameter by reference so that it directly effect the actual parameters.
问题:
当我们在功能名称之前使用引用(&
)时会发生什么?
Question:
What happens when we use a reference (&
) before a function name?
我有点困惑,因为我认为它将返回return的别名(变量名)。还是我错了?。
I'm a little bit confused, as in my opinion it will return the alias of return (variable name). Or am I wrong?.
'std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}'
推荐答案
在 C ++中,当在与它关联的函数的声明中的函数名称之前使用引用符号(&
)
In C++, when the ref-sign (&
) is used before the function name in the declaration of a function it is associated with the return value of the function and means that the function will return by reference.
int& foo(); // Function will return an int by reference.
在声明上下文中未使用时,将ref符号放在函数名称之前会导致调用 address-of 运算符返回函数的地址。这可以用于例如创建指向函数的指针。
When not used within a declaration context, putting the ref-sign before a function name results in calling the address-of operator returning the address of the function. This can be used to e.g. create a pointer to a function.
// Some function.
int sum(int a, int b) {
return a + b;
}
int main() {
// Declare type func_ptr_t as pointer to function of type int(int, int).
using func_ptr_t = std::add_pointer<int(int, int)>::type;
func_ptr_t func = ∑ // Declare func as pointer to sum using address-of.
int sum = func(1, 2); // Initialize variable sum with return value of func.
}
在 C 中,唯一使用&
用于地址运算符。用C语言存在不引用。
In C, the only use of &
is for the address-of operator. References does not exist in the C language.
这篇关于使用“&” C ++中函数名称之前的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!