#include <iostream> using namespace std; int main() { int a = 10; cout << a << endl; int &b = a; b = 23; cout << a << endl; return 0; }
输出:
10 23
可见,程序中对a的引用b的操作,也是对变量a的操作。
注意:
要把引用的&跟取地址运算符&区分开来,引用并不是取地址的意思。
#include <iostream> using namespace std; //将 int* 型变量的引用作为参数, //相当于对原int*变量的操作 void swap(int* &p1,int* &p2){ int *temp = p1; p1 = p2; p2 = temp; } int main() { int a = 10,b = 23; int *p1 = &a,*p2 = &b; //p1 p2为指针变量,存放a b的地址 cout << *p1 << " " << *p2 << endl; swap(p1,p2);//函数参数为a b的地址,类型为int* cout << *p1 << " " << *p2 << endl; return 0; }
10 23 23 10
为了理解上的方便,可以“简单”地把int*型理解成unsigned int型,而直接交换这样的两个整型变量是需要加引用的。
注意:
引用是产生变量的别名,因此常量不可使用引用。于是上面的代码中不可以写成swap(&a,&b),而必须用指针变量pl和p2存放&a和&b,然后把指针变量作为参数传入。
另外,如果想要深入了解引用,我推荐一篇文章:https://blog.csdn.net/JayRoxis/article/details/73060770 作者总结的比较用心。
结构体定义
可以将若干不同数据类型的数据封装在一起,可以用来储存复合数据。可以将若干不同数据类型的数据封装在一起,可以用来储存复合数据。
struct Name{ //自定义的数据结构 };
struct person{ char name[10]; char gender; int age; }; person Jhon,Harry,students[10];
struct person{ char name[10]; char gender; int age; }Jhon,Harry,students[10]; //Jhon,Harry为结构体变量,students[10]为结构体数组变量
struct person{ char name[10]; char gender; int age; person* father;//结构体内可以定义结构体本身的指针类型的指针变量 }Jhon,Harry,students[10]; //Jhon,Harry为结构体变量,students[10]为结构体数组变量
访问结构体中的元素
方式一:
Jhon.name Jhon.gender Jhon.age
方式二:
Jhon->name Jhon->gender Jhon->age
结构体初始化
使用构造函数初始化
#include <iostream> #include <string.h> using namespace std; struct person{ char name[10]; char gender; int age; person(char* name_,char gender_,int age_){ strcpy(name,name_); gender = gender_; age = age_;} }; int main() { person a("green",'F',20); cout << a.name << " " << a.gender << " " << a.age << endl; return 0; }
在创建时,自行初始化
#include <iostream> #include <string.h> using namespace std; struct person{ char name[10]; char gender; int age; }; int main() { person a; strcpy(a.name,"white"); a.gender = 'M'; a.age = 21; cout << a.name << " " << a.gender << " " << a.age << endl; return 0; }