指针数组
1.用int*p表示一个int[]
int main() {
int arr[] = {1, 3, 6, 5, 9};
int *p = arr;
cout << arr << endl;//0x99
cout << *p << endl;//1
cout << p << endl;//0x99
cout << &p << endl;//0x79
cout << *(p+1) << endl;//2
return 0;
}
结构体指针
利用操作符 ->
可以通过结构体指针
访问结构体属性
struct student {
string name;
int age;
int score;
} s3;
int main() {
student s1 = {"码云", 20, 30};
student s2 = {"马上", 30, 40};
student *p = &s1;//struct *p ,结构体 指针
cout << p->name << endl;
cout << p->age << endl;
cout << p->score << endl;
return 0;
}
引用
给变量起别名 , int &b = a; &看成起别名的操作
int a = 10;
int &b = a;
cout << a << endl;//10,输出时采用直接寻址a,输出操作数10
cout << b << endl;//10,输出时采用直接寻址b,输出操作数10
cout << &a << endl;//a=0xa56ffffb34
cout << &b << endl;//b=0xa56ffffb34
a和b的代表的地址是一样的
,只是变量的名称不一样
。
- 引用必须初始化
- 引用在初始化后,不可以改变
int main() {
int a = 10;
int b = 20;
int &c = a;
c = b;
cout << "&a = " << &a << endl;
cout << "&b = " << &b << endl;
cout << "&c = " << &c << endl;
return 0;
}
引用的本质是指针常量 int * const p;
因为编译器的语法优化,导致学习人员不容易看出。我的评价是,请哥哥帮忙不要优化
int & ref = a; // & = * const;
int * const ref与 int &ref 等价
void func(int& ref){
ref = 100;
}
int main(){
int a = 10;
int& ref = a;
ref = 20;
cout << "a:" << a << endl;
cout << "ref:" << ref << endl;
func(a);
return 0;
}
编译器自动优化,操作方便了,李姐变难了。才开自动挡,不方便。如果不嫌麻烦,
可以将&看成 * const