C++核心(面向对象)
引用
1.引用的基本概念
- 给变量起别名
- 数据类型 &别名 = 原名
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
b = 100;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
return 0;
}
2.引用的注意事项
- 引用必须初始化
- 引用初始化后不能修改
#include <iostream>
using namespace std;
int main()
{
int a = 10;
//int &b; //报错,没有进行初始化
int &b = a; //定义并进行初始化
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
int c = 100;
//int &b = c; //报错,初始化后不能修改
return 0;
}
3.引用做函数参数
- 函数传参时,可利用引用让形参修饰实参
- 可以简化指针修改实参
注:值传递;地址传递;引用传递(只有地址传递和引用传递可以修饰实参)
#include <iostream>
using namespace std;
void swap1(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swap2(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
void swap3(int &a, int &b)
{
int temp;
temp = a;
a =b;
b = temp;
}
int main()
{
int a = 10, b = 20;
swap1(a, b);
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
swap2(&a, &b);
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
swap3(a, b);
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
return 0;
}
4.引用做函数返回值
- 引用可以作为函数的返回值存在
注:局部变量的引用不能作为函数的返回值;函数调用可以作为左值
#include <iostream>
using namespace std;
int & test1()
{
int a = 10;
return a; /*局部变量存放在栈区,函数调用完之后内存被释放,
此变量已经不存在,所以主函数使用这个值是非法操作*/
}
int & test2()
{
static int a = 100;
return a; /*静态变量存放在全局区,整个程序结束之后内存才被释放,
所以可以作为函数的返回值*/
}
int main()
{
int &b = test1();
cout<<"b = "<<b<<endl; //编译器保留的值
cout<<"b = "<<b<<endl; //出错,非法操作
int &c = test2(); //作为函数调用的左值
cout<<"c = "<<c<<endl;
cout<<"c = "<<c<<endl;
cout<<"c = "<<c<<endl; //不会出错
return 0;
}
5.引用的本质
- 引用的本质是C++内部实现的指针常量
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a; //引用的实质是指针常量,即int * const b = &a,则指针变量的指向不能改变,但值可以改变
cout<<"a = "<<a<<endl;
b = 20; //值发生改变,相当于*b = 20
cout<<"a = "<<a<<endl;
return 0;
}
6.常量引用
- 常量引用主要用来修饰形参,防止误操作
#include <iostream>
using namespace std;
void test1(int &a)
{
a = 100;
}
void test2(const int &a)
{
//a = 1000; // 常量指针只读,报错不能修改,防止误操作
}
int main()
{
int b = 10;
cout<<"b = "<<b<<endl;
test1(b); //可对b进行操作,引用传递,将其值修改
cout<<"b = "<<b<<endl;
test2(b);
cout<<"b = "<<b<<endl;
int c = 1000;
int &d = c; //正确
//int &d = 1000; //报错,非法操作
cout<<"d = "<<d<<endl;
const int &e = 10000; //正确,C++处理过程是申请一个中间变量,即int temp = 1000,然后int &d = temp
cout<<"e = "<<e<<endl;
return 0;
}