c++ 左值 右值

#include <iostream>

// 返回的是右值
int GetValue()
{
    return 10;
}

// 返回的是一个引用,说明是有地址的
// 返回的是一个左值引用
int& GetValue2()
{
    static int value = 10;
    return value;
}

void SetValue(int value) 
{

}

// 传递一个左值引用
void SetValue2(int& value) 
{

}

// 传递一个左值引用
void SetValue3(const int& value) 
{

}

int main2()
{
    int i = 10;

    //10 = i;

    int a = i;

    int t = GetValue();

    //GetValue() = 5;

    // 左值引用可以赋值
    GetValue2() = 5;

    // 传递左值
    SetValue(i);
    // 传递右值
    // 这种情况会创建一个临时左值
    SetValue(10);

    SetValue2(i);
    // 非常量引用的初始值必须为左值
    // 非const 引用的初始值必须为左值
    // SetValue2(10);

    //non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
    // 因为b需要一个地址,而10没有地址,所以报错
    // int& b = 10;
    const int& b = 10; // 实际情况是

    // 实际上还是创建了一个左值
    int temp = 10;
    const int& b1 = temp;

    // 参数部分,实际上就是上面例子的const int& b
    // 从bnf也可以想到是这样
    SetValue3(i);
    SetValue3(10);
    
}


// 字符串的例子
// 可以用这个来检测某个值是否为左值
// 左值引用
void PrintName(std::string& name)
{
    std::cout << name << std::endl;    
}

// 这就是为什么很多c++写成常量引用,因为要兼容左值变量和临时右值
void PrintName2(const std::string& name)
{
    std::cout << name << std::endl;    
}

// 右值引用,只接受右值
void PrintName3(const std::string&& name)
{
    std::cout << name << std::endl;    
}

int main()
{
    std::string firstName = "abc";
    std::string lastName = "Defasdfadf";

    std::string allName = firstName + lastName;

    PrintName(allName);

    //非常量引用的初始值必须为左值
    // 因为firstName + lastName 是右值
    //PrintName(firstName + lastName);

    PrintName2(firstName + lastName);

    // 因为allName是左值
    // PrintName3(allName);
    PrintName3(firstName + lastName);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值