博罗惠州网站建设,网站开发多钱,企业网站如何做seo,开发网站开发工程师招聘c核心编程引用2.引用2.1引用的基本使用2.2引用注意事项2.3引用做函数参数2.4引用做函数返回值2.5引用的本质2.6常量引用2.引用
2.1引用的基本使用
作用: 给变量起别名语法:数据类型 别名 原名演示#includeiostream
using namespace std;
void func();i…
c核心编程引用2.引用2.1引用的基本使用2.2引用注意事项2.3引用做函数参数2.4引用做函数返回值2.5引用的本质2.6常量引用2.引用
2.1引用的基本使用
作用: 给变量起别名语法:数据类型 别名 原名演示#includeiostream
using namespace std;
void func();int main()
{func();system(pause);return 0;
}void func()
{int num 10;cout num endl;// 10int num2 num;cout num endl;// 10cout num2 endl;// 10num2 12;cout num endl;// 12cout num2 endl;// 12
}2.2引用注意事项
引用必须初始化引用在初始化后不可以改变无论是操作别名还是操作原名都是操作同一块内存
#includeiostream
using namespace std;int main()
{int num1 12;int num2 25;// 1.引用必须初始化// int num; // 2.一旦初始化就不可以更改(引用)int num num1; // 赋值操作不是更改引用num num2; cout num endl; // 25cout num1 endl; // 25cout num2 endl; // 25system(pause);return 0;
}2.3引用做函数参数
函数传参时可以利用引用的技术让形参修饰实参可以简化指针修改实参
#includeiostream
using namespace std;//交换函数
//1.值传递
void SwapNum(int a, int b);
//2.地址传递
void SwapAdd(int* a, int* b);
//3.引用传递
void SwapRef(int a, int b);int main() {int a 10;int b 20;SwapNum(a, b);// 值传递形参不会修饰实参cout a a endl;// 10cout b b endl;// 20SwapAdd(a, b);// 地址传递形参会修饰实参的cout a a endl;// 20cout b b endl;// 10SwapRef(a, b);// 引用传递形参也会修饰实参的cout a a endl;// 10cout b b endl;// 20system(pause);return 0;
}void SwapNum(int a, int b) {// 形参发生改变int temp a;a b;b temp;
}
void SwapAdd(int* a, int* b) {int temp *a;*a *b;*b temp;
}
void SwapRef(int a, int b) {int temp a;a b;b temp;
}2.4引用做函数返回值
引用是可以作为函数的返回值存在的不要返回局部变量引用函数调用为左值
#includeiostream
using namespace std;// 引用做函数的返回值
// 1.不要返回局部变量
int test_1();// 2.函数的调用可以作为左值
int test_2();int main() {int ref test_1();// 第一次操作的结果是正常的是因为编译器做了保留cout ref ref endl; // 第二次结果错误因为a的内存已经释放了cout ref ref endl;int ref2 test_2();cout ref2 ref2 endl; // 10cout ref2 ref2 endl; // 10cout ref2 ref2 endl; // 10//如果函数的返回值是引用这个函数调用可以作为左值test_2() 1000;cout ref2 ref2 endl; // 1000system(pause);return 0;
}int test_1() {int a 10;return a;
}int test_2() {// 静态变量存放在全局区全局区上的数据在程序结束后释放static int a 10;return a;
}2.5引用的本质
本质: 引用的本质在C内部实现是一个指针常量
#includeiostream
using namespace std;
void func(int ref);int main() {int a 10;int ref a;ref 20;cout a a endl; // 20cout ref ref endl; // 20func(a);cout ref ref endl; // 100system(pause);return 0;
}void func(int ref) {ref 100;
}2.6常量引用
作用: 常量引用主要用来修饰形参防止误操作在函数形参列表中可以加const修饰形参防止形参改变实参
#includeiostream
using namespace std;void showValue(int value);int main() {// 常量引用// 使用场景: 用来修饰形参防止误操作int a 10;//int ref 10; //error,引用必须引一块合法的内存空间int ref a;// 加上const之后 编译器将代码修改 int temp 10;const int ref temp;const int ref2 10;// error, 加上const之后变为只读不可修改// ref2 20;int num 1000;showValue(num);system(pause);return 0;
}
void showValue(int value) {cout value value endl; // 1000
}// 增加const的目的是为了让形参不被修改
void showValue(const int value) {// value 120;cout value value endl; // 1000
}