#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);
}
c++ 左值 右值
最新推荐文章于 2024-02-28 20:04:50 发布