'&' 的使用C++中函数名前的运算符 [英] Use of '&' operator before a function name in C++

查看:22
本文介绍了'&' 的使用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?

我有点困惑,因为在我看来它会返回返回的别名(变量名).还是我错了?.

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.

当不在声明上下文中使用时,将引用符号放在函数名称之前会导致调用 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 = &sum; // 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屋!

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