您的位置:首页 > 其它

指针、指针常量与常量指针的理解

2018-01-19 14:13 218 查看
#include<iostream>
using namespace std;

int main(){
int i = 1;
const int j = 2;
const int k = 3;
int l = 4;

/*========================普通指针,指针常量,常量指针========================*/
int *p = &i;//普通指针
cout << "the value of *p is: "<<*p<<"\n"<<endl;//输出为1
i = 10;
cout << "the value of *p is: "<<*p<<"\n"<<endl;//输出为10
p = &l;
cout << "now the value of *p is: "<<*p<<"\n"<<endl;//输出为4

const int *q = &j;//指向常量的指针,即指针常量
cout<<"the value of *q is: "<<*q<<"\n"<<endl;//输出为2
//*q = 10; wrong
//j = 20; wrong,j为常量
//int *y = &j;//wrong,要存放常量对象的地址,只能使用指向常量的指针q,不能使用普通指针y
q = &l;//指向常量的指针可以指向不是常量的对象,但不能通过*q改变l的值
//(因为指向常量的指针本身是用来指向常量的,使用*q不能改变常量的值,
//即使q指向普通对象也是不能用*q去改变普通对象的值)
cout<<"now the value of *q is: "<<*q<<"\n"<<endl;//输出为4
l=50;//right,但可以直接改变对象的值
cout<<"now the value of *q is: "<<*q<<"\n"<<endl;//输出为50

int *const n = &i;//n常量指针,指向的地址不能变化,但指向的地址的值可以变
//(n存放的地址为常量,不能变,但存放地址的值可以变)
cout<<"the value of *n is: "<<*n<<"\n"<<endl;//输出为10
//n = &l;wrong,指向的地址变化了
i=40;//right,n指向i的地址的值可以变
cout<<"the value of *n is: "<<*n<<"\n"<<endl;//输出为40
*n = 100;//right,根据其所指的是常量或非常量而定,如果n所指的是常量,则*n不能变
cout<<"the value of *n is: "<<*n<<" and i is: "<<i<<"\n"<<endl;//输出都为100

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: