本文共 1432 字,大约阅读时间需要 4 分钟。
语法: 数据类型 &别名 = 原名
本质: 在c++内部实现是一个指针常量
一、变量
引用必须初始化
引用在初始化后,不可以改变
#include#include #include using namespace std;int main(int argc, char const *argv[]){ int a = 10; int b = 20; //int &c; //错误,引用必须初始化 int &c = a; //一旦初始化后,就不可以更改 c = b; //这是赋值操作,不是更改引用,将a的值更改为b;指针为int * p = &a; *p = b; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; system("pause"); return 0;}
二、常量
常量引用主要用来修饰形参,防止误操作;在函数形参列表中,可以加const修饰形参,防止形参改变实参
#include#include #include using namespace std;//引用使用的场景,通常用来修饰形参void showValue(const int& v) { //v += 10; //const修饰的变量,指向v的内存地址,其值无法被改变; cout << v << endl;}int main(int argc, char const *argv[]){ const int& ref = 10; //ref = 100; //加入const后不可以修改变量 cout << ref << endl; //函数中利用常量引用防止误操作修改实参 int a = 10; showValue(a); system("pause"); return 0;}
三、函数引用
code sample 在 的test04函数里有实现;简单说其作用类似指针;
作用:引用是可以作为函数的返回值存在的
注意:不要返回局部变量引用
用法:函数调用作为左值
//返回局部变量引用int& test01() { int a = 10; //局部变量 return a;}//返回静态变量引用int& test02() { static int a = 20; return a;}int main() { //不能返回局部变量的引用 int& ref = test01(); cout << "ref = " << ref << endl; cout << "ref = " << ref << endl; //如果函数做左值,那么必须返回引用 int& ref2 = test02(); cout << "ref2 = " << ref2 << endl; cout << "ref2 = " << ref2 << endl; test02() = 1000; cout << "ref2 = " << ref2 << endl; cout << "ref2 = " << ref2 << endl; system("pause"); return 0;}
转载地址:http://ouagj.baihongyu.com/