大家好:
衷心希望各位点赞。
您的问题请留在评论区,我会及时回答。
一、const修饰指针
const修饰指针,有三种情况:
1、const修饰指针,常量指针。
2、const修饰常量,指针常量。
3、const既修饰指针,又修饰常量。
技巧:看const右侧紧跟的是指针还是常量,是指针就是常量指针,是常量就是指针常量。
二、常量指针
特点:指针的指向可以更改,但是指针指向的值不可以更改。
#include <iostream>
#include <Windows.h>
using namespace std;
int main(void) {
int a = 10;
int b = 20;
const int* p = &a; //定义常量指针,指向变量a的地址
cout << *p << endl;//打印10
p = &b;//可以更改常量指针的指向
cout << *p << endl;//打印20
*p = 30; //错误,不能更改常量指针指向的值
system("pause");
return 0;
}
二、指针常量
特点:指针的指向不可以更改,但是指针指向的值可以更改。
#include <iostream>
#include <Windows.h>
using namespace std;
int main(void) {
int a = 10;
int b = 20;
int* const p = &a; //定义指针常量,指向变量a的地址
cout << *p << endl;//打印10
*p = 30; //指针常量指向的值可以更改
cout << *p << endl;//打印30
p = &b;//错误,指针常量的指向不可更改
system("pause");
return 0;
}
三、const既修饰指针,又修饰常量
特点:指针的指向和指针指向的值都不可以更改。
#include <iostream>
#include <Windows.h>
using namespace std;
int main(void) {
int a = 10;
int b = 20;
const int* const p = &a; //指向变量a的地址
cout << *p << endl;//打印10
*p = 30; //错误,指针指向的值不可以更改
p = &b;//错误,指针指向不可更改
system("pause");
return 0;
}