引用
一、主要作用
用作函数的形参
a)未使用“引用”作为形参
1 void SetValue(int _Height)
2 {
3 _Height=99;
4 }
5 int Height=10;
6 SetValue(Height);
7 cout<<"设置之后Height的值为:"<<Height<<endl;
8 system("pause");
9 return 0;
运行结果:
内存分配:
b)使用“引用”作为形参
1 void SetValue(int &_Height)
2 {
3 _Height=99;
4 }
5 int Height=10;
6 SetValue(Height);
7 cout<<"设置之后Height的值为:"<<Height<<endl;
8 system("pause");
9 return 0;
运行结果:
内存分配:
二、特点(非const引用)
a)定义的时候必须使用同类型的某个对象对其初始化
1.正常情况下:
1 int Amount=10;
2 int &Ref_Amount=Amount;
3
4 cout<<"测试程序: "<<Ref_Amount<<endl;
5 system("pause");
6 return 0;
运行结果:
2.未进行初始化时:
1 int Amount=10;
2 int &Ref_Amount;
3
4 cout<<"测试程序: "<<Ref_Amount<<endl;
5 system("pause");
6 return 0;
运行结果:
3.初始化时,使用的不是对象
1 int Amount=10;
2 int &Ref_Amount=100;
3
4 cout<<"测试程序: "<<Ref_Amount<<endl;
5 system("pause");
6 return 0;
运行结果:
4.初始化时,使用的对象类型不匹配
1 int Amount=10;
2 double point=66.999;
3
4 int &Ref_Amount=point;
5
6 cout<<"测试程序: "<<Ref_Amount<<endl;
7 system("pause");
8 return 0;
运行结果:
b)指向的单元是可以改变的
1 int Amount=10;
2 int &Ref_Amount=Amount;
3
4 Ref_Amount=88;
5
6 cout<<"Amount的值为:"<<Amount<<endl;
7 system("pause");
8 return 0;
运行结果:
三、对比“const引用”与“非const引用”
注:“const引用”实质就是指向“const对象”的引用,所有特性,都保证了“const对象”的值不可改变
a)“const引用”指向的单元,值不可改变;“非const引用”指向的单元,值可改变
1.“const引用”指向的单元,值不可改变
1 const int Amount=10;
2 const int &Ref_Amount=Amount;
3
4 Ref_Amount=88;
5
6 cout<<"Amount的值为:"<<Amount<<endl;
7 system("pause");
8 return 0;
运行结果:
2.“非const引用”指向的单元,值可改变
1 int Amount=10;
2 int &Ref_Amount=Amount;
3
4 Ref_Amount=88;
5
6 cout<<"Amount的值为:"<<Amount<<endl;
7 system("pause");
8 return 0;
运行结果:
b)“const引用”初始化时可以使用类型不匹配的对象;“非const引用”必须使用同类型的对象初始化
原因:“const引用”本身只是个普通的指针,它不允许有类似于的对目标对象的赋值操作,不会产
生对不同类型对象单元的修改操作
1 double point=8.77;
2 const int &Ref_pointInt=point;
3
4 cout<<"Ref_pointInt的值为:"<<Ref_pointInt<<endl;
5 cout<<"point的值为:"<<point<<endl;
6 system("pause");
7 return 0;
运行结果: