1. 首先需要明白的便是&符号
想完全弄明白的时候细究这篇博客。
https://blog.youkuaiyun.com/msdnwolaile/article/details/50890365
现在在指针的章节,我们要先知道&符号代表的是返回操作数的内存地址。
2. 符号 *
“*”被叫做间接运算符,也可以叫间接引用。
比如说 cout << *Ptr <<endl;
代表的便是输出Ptr指针所指向的内存空间内所存储的数据。
3.以下为测试的一个小程序
#include<iostream>
using namespace std;
int main(){
int a;
int *ptr;
a = 7;
ptr = &a;
cout << "The adress of a is" << &a
<< "\nThe vaule of ptr is " << ptr;
cout << "\n\nThe value of a is" << a
<< "\nThe value of *ptr is" << *ptr;
cout<<"\nShow that * and & are inverses of "
<<"\n*&ptr = "<<*&ptr
<<"\n&*ptr = "<<&*ptr<<endl;
}
输出的结果则是
The adress of a is0x7ffd882dd9bc
The vaule of ptr is 0x7ffd882dd9bc
The value of a is7
The value of *ptr is7
Show that * and & are inverses of
*&ptr = 0x7ffd882dd9bc
&*ptr = 0x7ffd882dd9bc
songsujing@songsujing-UX303LN:~/yuan$ gedit Ptr.cpp
从结果中可以看出一些东西,也能理解的更加深刻,值得注意的便是“&”“*”符号作用可以相互抵消。
4.接着使用指针的按引用传递方式
接收地址实参的函数,必须定义指针参数来接收地址,并把该地址存储到对应的局部变量指针,要记住是没有返回值的。
#include<iostream>
using namespace std;
void cubeV(int *);
int main(){
int a ;
a = 5;
cubeV(&a);
cout<<"the cube of a is "<<a;
}
void cubeV(int *Ptr){
*Ptr = *Ptr * *Ptr * *Ptr;
}
运行的结果为
the cube of a is 125