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

标签 c++ function reference

引用定义对象的替代名称。引用类型“指的是” 另一种。我们通过编写 &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 = &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 语言中存在引用。

关于c++ - 在 C++ 中的函数名前使用 '&' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23776784/

相关文章:

c++ - 编译器警告 re : references to local variables

c++ - 将 pardiso 求解器与特征一起使用

python - 复制 pandas 数据框和系列

C++ 实例 VS 指针 VS 引用

function - 为什么我不能直接将地址运算符 (&) 应用于函数返回值

c++ - 带有指向参数的指针的基本函数重载给出错误

c++ - 如何允许模板函数具有 friend(-like) 访问权限?

c++ - setContextProperty 和 setProperty of object 的区别

c++ - Rapidjson,在另一个数组的数组中获取一个值

c++ - 我怎样才能初始化一个对象