小编Avi*_*ick的帖子

Rvalue和Lvalue参考

我有一个函数printInt,如下所示.

void printInt(const int& a)
{
    cout<<a<<endl;
}
Run Code Online (Sandbox Code Playgroud)

当我使用以下参数调用函数时

int a=5;
printInt(a);
printInt(5);
Run Code Online (Sandbox Code Playgroud)

它完美地运作.但是当我将函数定义更改为

void printInt(int& a)
{
    cout<<a<<endl;
}
Run Code Online (Sandbox Code Playgroud)

这给通话带来了错误printInt(5).现在我的问题是为什么const int&是左值和左值引用,而int&只是左值引用.据我所知,int&&是一个右值参考.那么单个&可以如何引用右值参考?

总结一下我的问题:

  1. 左值参考参数

    void printInt(int& a)
    {
        cout<<a<<endl;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. Rvalue参考参数

    void printInt(int&& a)
    {
        cout<<a<<endl;
    }    
    
    Run Code Online (Sandbox Code Playgroud)
  3. 左值和左值.但怎么样?

    void printInt(const int& a)
    {
        cout<<a<<endl;
    }
    
    Run Code Online (Sandbox Code Playgroud)

c++ c++11

4
推荐指数
1
解决办法
160
查看次数

"[&]"在C++中意味着什么?

我正在阅读源代码,它包含以下几行.

auto updateSlack = [&](const char slack_type, const double s) {
    if (slack_type == 'e') {
        wns.early_slack = min(s, wns.early_slack);
        tns.early_slack += s;
    }
    else if (slack_type == 'l') {
        wns.late_slack = min(s, wns.late_slack);
        tns.late_slack += s;
    }
};
Run Code Online (Sandbox Code Playgroud)

我对"="运算符后的"[&]"符号感到困惑.任何人都能说出这究竟是什么意思?

c++ c++11

-6
推荐指数
1
解决办法
138
查看次数

标签 统计

c++ ×2

c++11 ×2