关于在C++中"&"的引用作用
在C语言中的"&"
在C语言中"&"为取址符,通常和指针配套使用。例如在函数的调用时中可以将变量的地址传送给函数,从而可以使函数可以改变参数的值。
在C++中新的改变
我们在C++中可以将"&"解释为引用型,可以理解为取别名。既是对原有空间重新起一个名字,并且通过这个变量名可以对变量进行操作。我们在下面的一个例子中体现出来
#include<iostream>
using namespace std;
int main(){
int a = 8;
int &b = a; //将a的地址给&b
cout<<&b; //会输出a的地址
cout<<b; //会输出a的值为8
}
在数据结构中的应用:
这里用简单的顺序表的实现来表示
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int Status;
typedef int ElemType;
typedef struct SqList{
ElemType elem[MAXSIZE];
int Length;
}SqList;
void CreateList(SqList* &L, int n);
void PrintLisT(SqList *L);
int main(void)
{
SqList* L;
int Len;
cout<<"Please input your number of your list: "<<endl;
cin>>Len;
CreateList(L, Len);
PrintLisT(L);
return 0;
}
void CreateList(SqList* &L, int n){
L = new SqList;
int i = 0;
cout<<"Your number is : "<<n<<endl;
for(i=0; i<n; i++){
cout<<"Please input your number: "<<endl;
cin>>L->elem[i];
}
L->Length = n;
cout<<"The length of your List: "<<L->Length<<endl;
}
void PrintList1(SqList* L){
int i=0;
for(i=0; i<L->Length; i++){
cout<<L->elem[i]<<" ";
}
}
几点特殊的说明
- 这里 SqList* L; 为声明了一个指针变量为L且指向SqList这种类型。
- 这里 (SqList* &L); 为参数列表中声明了一个临时的指针变量,但是和在调用处读入的那个指针是同地址不同名,既是可以通过这个来改变原来指针的值
- 在主函数调用CreateList函数的时候,因为我们已经 定义 SqList* L;则在传入的时候传入L就行,因为函数所需要的参数就是为指向SqList这种类型空间的指针,既是L,而不用加上*L 或者 &L。
- 在这里 也可以不用这种方式,因为是传给函数一个指针,我们可以给函数传入一个实例化, 或者实例化之后再传入。
#include<iostream>
using namespace std;
typedef struct sqlist{... //如上
void CreateList(SqList L, ...)
int main(void){
SqList L;
CreateList(L)
}
- 关于实例化:一定要注意你的指针指向啥 你就 new 啥,比如 在单链表中:L = new LNode; 因为L是指向LNode这种类型的指针。