2

【笔记】C++引用

 1 year ago
source link: https://feiju12138.github.io/2022/08/14/C-%E5%BC%95%E7%94%A8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++引用学习笔记

  • 给变量起别名
  • 引用的本质是一个指针常量
  • 引用必须初始化
  • 引用一旦初始化后,就不可以更改
// 引用一个合法的内存空间
数据类型 &别名 = 原名;
// 引用的本质是一个指针常量
//数据类型 * const 别名 = &原名;

// 通过引用操作数据
别名 = 值;
// 内部自动解引用
*别名 = 值;

引用做函数的参数

返回值类型 函数名(数据类型 &形参名)
{
return 返回值;
}

int main()
{
数据类型 变量名 = 值;
函数名(变量名);
return 0;
}

引用做函数的返回值

  • 不要返回局部变量的引用
  • 函数的调用可以作为左值
返回值类型& 函数名()
{
数据类型 变量名 = 值;
return 变量名;
}

int main()
{
数据类型 &变量名 = 函数名();
函数名() = 值;
return 0;
}
  • 修饰形参,防止形参改变实参
// 引用
const 数据类型 & 别名 = 值;
// 实质上
//数据类型 temp = 值; const 数据类型 & 别名 = temp;
数据类型 函数名(const 数据类型 &形参名)
{
...
}

哔哩哔哩——黑马程序员


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK