本文共 2438 字,大约阅读时间需要 8 分钟。
2. 引用
学习目的:取代C中的指针。
目录
2.1 引用的基本使用方法
数据类型 &别名 = 原名
int main() { int a = 10; // 创建引用 int& b = a; cout << "a = " << a << endl; cout << "b = " << b << endl << endl; b = 100; cout << "a = " << a << endl; cout << "b = " << b << endl << endl; system("pause"); return 0;}---------------------------------------------------------------a = 10b = 10a = 100b = 100请按任意键继续. . .
2.2 引用注意事项
示例:
int a = 10;int &b = a;1.引用必须要初始化 int &b; // 错误的2.引用一旦初始化后,就不可以更改了 &b = c; // 语法错误 b = c; // 并不是更改引用,而是赋值操作
2.3 引用做函数参数
// 值传递void swap01(int a, int b){ int temp = a; a = b; b = temp;}// 地址传递void swap02(int* a, int* b){ int temp = *a; *a = *b; *b = temp;}// 引用传递void swap03(int &a, int &b){ int temp = a; a = b; b = temp;}int main() { int a = 10,b = 20; cout << "a = " << a << endl; cout << "b = " << b << endl << endl; //swap01(a, b); //swap02(&a, &b); swap03(a, b); cout << "a = " << a << endl; cout << "b = " << b << endl << endl; system("pause"); return 0;}--------------------------------------------------------------------------a = 10b = 20a = 20b = 10请按任意键继续. . .
2.4引用做函数返回值
// 不要返回局部变量的引用。int& test1(){ int a = 10; return a;}int main() { int& temp = test1(); cout << "temp = " << temp << endl; cout << "temp = " << temp << endl; cout << "temp = " << temp << endl; cout << "temp = " << temp << endl; system("pause"); return 0;}------------------------------------------------------temp = 10temp = 2050341264temp = 2050341264temp = 2050341264请按任意键继续. . .
int& test1(){ static int a = 10; // 静态变量存放于全局区 return a;}int main() { int& temp = test1(); cout << "temp = " << temp << endl; cout << "temp = " << temp << endl; test1() = 1000; // 如果函数的返回值是引用,这个函数调用可以作为左值 cout << "temp = " << temp << endl; cout << "temp = " << temp << endl; system("pause"); return 0;}--------------------------------------------------------------------temp = 10temp = 10temp = 1000temp = 1000请按任意键继续. . .
2.5 引用的本质
本质:引用的本质在C++内部实现是一个指针常量。
解引用的过程在编译器处理。
2.6 常量引用
int& ref = 10; // 这种写法编译器会报错const int& ref = 10; // 相当于 int temp = 10; const int& ref = temp;ref = 20; // 编译器会报错。加const后变为只读,不可修改
int showValue(const int& a){ a += 10; // 这句编译器会报错,常量引用的值不可修改 cout << a << endl; return 0;}
相关教程
转载地址:http://onqe.baihongyu.com/