引用定义对象的替代名称。引用类型“指的是”
另一种。我们通过编写 &d
形式的声明符来定义引用类型,
其中 d
是声明的名称。
接下来是引用不是对象。相反,引用只是已存在对象的另一个名称。所以我们将使用这些引用通过引用传递参数,以便它直接影响实际参数。
问题:
当我们在函数名称之前使用引用 (&
) 时会发生什么?
我有点困惑,因为在我看来它会返回 return 的别名(变量名)。还是我错了?
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++ 中,当引用符号 (&
) 在函数的声明中的函数名称之前使用时,它是关联的带有函数的返回值,意味着函数将通过引用返回。
int& foo(); // Function will return an int by reference.
当不在声明上下文中使用时,将引用符号放在函数名称之前会导致调用 address-of 运算符返回函数的地址。这可以用于例如创建指向函数的指针。
// 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 语言中不存在引用。
关于c++ - 在 C++ 中的函数名前使用 '&' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23776784/