2.引用
引用可看作一个已定义变量的别名。
int a = 1;
int &b = a; // int * const b = &a; 必须初始化
b = 2; // *b = 2;
定义引用时必须用其它变量初始化。
这是c++的语法范畴,是c++编译器对c的扩展。
/*
交换函数示例
*/
//指针实现
void swap(int *a,int *b)
{
int c = 0;
c = *a;
*a = *b;
*b = c;
}
swap(&x,&y);
//引用实现
void swap(int &a,int &b)
{
int c = 0;
c = a;
a = b;
b = c;
}
swap(x,y); //这里,a,b就是x,y的别名。
引用有更好的可读性和实用性,一些场合可以替换指针。
2.1 引用本质
int a = 1; int &b = a; // int * const b = &a; 必须初始化
这是用常量指针实现的,&a==&b
,是c++编译器帮我们取了地址。
而且,引用也占空间,大小与指针相同。
struct Person{
int age;
int &a;
};
cout<<sizeof(Person)<<endl;
2.2 分类
引用分为普通引用和常引用
// 普通引用
int &b = a;
// 常引用
const int &b = a; //const int * const b
// 常引用还有第2种初始化方法
int &b = 1; //报错,字面量1没有内存地址,无法取别名。
const int &c = 2; //c++编译器会分配空间
//可以用来替换宏定义
2.3 间接赋值
间接赋值是指针的最大意义
/*
复习:间接赋值的3个条件
*/
int a = 1;int *p = NULL; // 1.定义实参和形参
p = &a; //2. 实参地址传给形参
*p = 2; //3 形参间接修改实参的值
/*
3写在函数里,则是函数调用。
刚才用引用实现的交换函数,则是把2和3统一。
*/
2.4 函数返回值为引用
若返回栈变量:
- 不能成为其它引用的初始值
- 不能做左值
若返回静态变量或全局变量:
- 可以成为其它引用的初始值
- 既可以做左值,也可以做右值
做右值
#include<iostream>
using namespace std;
int& retRef(){
int a = 3;
return a;
}
int main()
{
int ref1 = 0;
ref1 = retRef();
cout<<"ref1:"<<ref1<<endl;
int &ref2 = retRef(); //调用后清理函数的栈
cout<<"ref2:"<<ref2<<endl; //可能有乱码
cin.get();
return 0;
}
/*
这段代码,release和debug结果不一样
ref1会接受局部变量a的副本;ref2接收地址。
*/
#include<iostream>
using namespace std;
int f1(){
static int a = 1;
a++;
return a;
}
int& f2(){
static int a = 1;
a++;
return a;
}
int main()
{
int f1ret1 = 0;
int f1ret2 = 0;
int f2ret1 = 0;
f1ret1 = f1();
f1ret2 = f1();
f2ret1 = f2();
int& f2ret2 = f2();
cout<<"f1()-1:"<<f1ret1<<endl;
cout<<"f1()-2:"<<f1ret2<<endl;
cout<<"f2()-1:"<<f2ret1<<endl;
cout<<"f2()-2:"<<f2ret2<<endl;
cin.get();
return 0;
}
做左值
#include<iostream>
using namespace std;
int& f2(){
static int a = 1;
a++;
cout<<a<<endl;
return a;
}
int main()
{
f2() = 10;
f2() = 10;
f2() = 10;
cin.get();
return 0;
}
//输出 2 11 11
2.5 指针的引用
#include <iostream>
using namespace std;
struct Person{
int age;
};
void getPerson1(Person **argp){
//c:second rank pointer
//这种方法需要了解栈和堆的知识
Person* tmp = NULL;
tmp = (Person*)malloc(sizeof(Person));
if(tmp == NULL){
cout<<"error 1!"<<endl;
return;
}
tmp->age = 1;
*argp = tmp;
tmp = NULL;
}
void getPerson2(Person* &argp){
//c++:reference
argp = (Person*)malloc(sizeof(Person));
if(argp == NULL){
cout<<"error 2!"<<endl;
return;
}
argp->age = 2;
}
int main()
{
Person* p = NULL;
getPerson1(&p);
if(p != NULL){
cout<<"p->age:"<<p->age<<endl;
}
free(p);
p = NULL;
getPerson2(p);
if(p != NULL){
cout<<"p->age:"<<p->age<<endl;
}
free(p);
p = NULL;
cin.get();
return 0;
}