繁体   English   中英

在C ++中的函数名之前使用'&'运算符

[英]Use of '&' operator before a function name in C++

引用定义了对象的备用名称。 引用类型“指”另一种类型。 我们通过编写形式&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 ++中 ,当在函数声明中的函数名之前使用ref-sign( & )时,它与函数的返回值相关联,意味着函数将通过引用返回

int& foo(); // Function will return an int by reference.

如果未在声明上下文中使用,则在函数名称前面放置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 = &sum; // Declare func as pointer to sum using address-of.
    int sum = func(1, 2);   // Initialize variable sum with return value of func.
}

C中&唯一使用的是address-of运算符。 C语言中存在引用。

C&func ,其中func是一个函数,它计算函数的地址,该函数可以分配给一个函数指针,该函数指针指向一个与函数func具有相同签名的函数。

int func(float);

int (*fp)(float) = &func; 
// equivalent to
int (*fp)(float) = func;
'// return the plural version of word if ctr is greater than 1
string make_plural(size_t ctr, const string &word,
                           const string &ending)
{
    return (ctr > 1) ? word + ending : word;
}'

此函数的返回类型为string,表示将返回值复制到调用站点。 此函数返回word的副本,或者返回由添加单词和结尾产生的未命名临时字符串。

与任何其他引用一样,当函数返回引用时,该引用只是它引用的对象的另一个名称。 作为示例,考虑一个函数,该函数返回对其两个字符串参数中较短者的引用:

'// return a reference to the shorter of two strings
const string &shorterString(const string &s1, const string
&s2)
{
    return s1.size() <= s2.size() ? s1 : s2;
}'

参数和返回类型是对const字符串的引用。 调用函数或返回结果时,不会复制字符串。

永远不要将引用或指针返回到本地对象

函数完成后,将释放其存储空间。 函数终止后,对本地对象的引用引用不再有效的内存:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM