Ali*_*786 7 c++ reference function
引用定义了对象的备用名称.引用类型"指"另一种类型.我们通过编写表单的声明符来定义引用类型&d,其中d是声明的名称.
接下来的事情是引用不是对象.相反,引用只是已存在对象的另一个名称.因此,我们将使用这些引用通过引用传递参数,以便它直接影响实际参数.
问题:
当我们在函数名之前使用reference(&)时会发生什么?
我有点困惑,因为在我看来它会返回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;
}'
Run Code Online (Sandbox Code Playgroud)
Snp*_*nps 16
在C++中,当在&函数声明中的函数名之前使用ref-sign()时,它与函数的返回值相关联,这意味着函数将通过引用返回.
int& foo(); // Function will return an int by reference.
Run Code Online (Sandbox Code Playgroud)
如果未在声明上下文中使用,则在函数名称前面放置ref-sign会导致调用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.
}
Run Code Online (Sandbox Code Playgroud)
在C中,唯一的用途&是address-of运算符.C语言中不存在引用.
在C,&func其中func函数求值为函数的地址,该函数可以分配给函数指针,该函数指针指向与函数具有相同签名的函数func.
int func(float);
int (*fp)(float) = &func;
// equivalent to
int (*fp)(float) = func;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10537 次 |
| 最近记录: |