小编use*_*499的帖子

返回&和没有区别是什么?

我仍然没有弄清楚&编译器中的工作原理。

为了弄清楚,我尝试分解下面的代码:

private:
        int data;
public:
int& at()
{
    return data;
}
int at()
{
    return data;
}

const int& result = mymay.at(); //call the two functions
Run Code Online (Sandbox Code Playgroud)

我发现int& at()返回一个地址,并int at()返回一个值;编译器首先将值写入内存,然后将“结果”的地址设置为该地址。所以我知道这int at()将返回一个副本。我也了解写作是最佳实践friend ostream& operator<<(ostream &os , const A &obj)

但我想知道是否正确:在以下代码中,A &get1()返回l-value,然后A get2()返回r-value

#include <iostream>
using namespace std;
class A
{
public:
    A &get1(){
        return *this;
    }
    A get2(){
        return *this;
    }
    friend ostream& operator<<(ostream …
Run Code Online (Sandbox Code Playgroud)

c++

0
推荐指数
1
解决办法
76
查看次数

标签 统计

c++ ×1