c++引用笔记

<code>#include <iostream>
using namespace std;


int main(void)
{
//引用基本数据类型
// 数据类型 &别名 = 原名


int a=10;
//创建引用
int &b=a;

cout< cout< b=100;

cout< cout<

//1.引用必须要初始化
// int &b; //错误的
int a=10; //int &b; 错误的
int &b=a;
//2.引用一旦初始化,不可以发生改变
int c=20;
b=c; //赋值操作,而不是更改引用

cout< cout< cout<



system("pause");
return 0;

}


//////////////////////////////////////////////////
#include <iostream>
using namespace std;

//交换函数

//1.值传递
void mySwap01(int a,int b)
{
int temp=a;
a = b;
b = temp;


cout< cout<}

//2.地址传递
void mySwap02(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

//3.引用传递
void mySwap03(int &a,int &b)
{
int temp = a;
a = b;
b = temp;
}
int main(void)
{
int a=10;
int b=20;
//mySwap01(a,b);//值传递,形参不会修饰实参
//mySwap02(&a,&b);//地址传递,形参会修饰实参的
mySwap03(a,b); //引用传递,形参会修饰实参的
cout< cout<

system("pause");
return 0;
}
/////////////////////////////////////////////
#include <iostream>
using namespace std;

//引用做函数的返回值
//1.不要返回局部变量的引用

int & test01()
{
int a=10; //局部变量存放在四区中的栈区
return a;
}

//2.函数的调用可以作为左值
int & test02()
{
static int a=10;//静态变量,存放在全局区,全局上的数据在程序结束后会系统释放
return a;
}
int main(void)
{


//int &ref =test01();
//cout <
int &ref2 = test02(); //如果函数的返回值是引用,这个函数调用可以作为左值
cout < cout <
test02()=1000;
cout < cout <

system("pause");
return 0;
}
/////////////////////////////////////
#include <iostream>
using namespace std;

//引用的本质:引用的本质在c++内部实现是一个指针常量
//发现是引用,转换为int * const ref = &a;
void func(int& ref)
{
ref = 100; //ref是引用,转换为*ref = 100;
}

int main(void)
{
int a=10;

int& ref = a;
//自动转换为int * const ref = &a;指针常量是指针指向不可更改,也说明为啥引用不可更改

ref = 20; //内部发现ref 是引用,自动帮我们转换为:*ref = 20;

cout < cout <
func(a);
cout < cout <
system("pause");
return 0;

}
////////////////////////
//引用使用的场景,通常用来修饰形参
void showValue(const int& v) {
//v += 10;
cout << v << endl;
}

int main() {

//int& ref = 10; 引用本身需要一个合法的内存空间,因此这行错误
//加入const就可以了,编译器优化代码,int temp = 10; const int& ref = temp;
const int& ref = 10;

//ref = 100; //加入const后不可以修改变量
cout << ref << endl;

//函数中利用常量引用防止误操作修改实参
int a = 10;
showValue(a);

system("pause");

return 0;
}/<iostream>/<iostream>/<iostream>/<iostream>/<code>


分享到:


相關文章: