#include <iostream>
using namespace std;
//const是常量的意思,被其修饰的变量不可修改
//const int age = 10;//必须定义时指定其值,age不能修改
//如果修饰的是类、结构体(的指针),其成员也不可以更改
struct Date{
int year;
int month;
int day;
};
int main() {
//Date d = {2021, 9, 16};//定义结构体变量,C语言需要在前面加上struct
//d.year = 2022;//成员可以更改
//const Date d = { 2021, 9, 16 };//定义结构体变量
//d.year = 2022;//成员不可以更改
Date d1 = { 2021, 9, 16 };
Date d2 = { 2021, 9, 17 };
Date *p = &d1;//指针p(指针类型为Date *)指向结构体d1,d1的地址值复制给指针p(若加const,下三行会报错)
p->year = 2022;//利用指针p修改year(指针修改所指向结构体的成员)
(*p).month = 5;//*p表示取出指针指向的对象,这里取出d1
*p = d2;//将d2复制给d1
cout << d1.year << endl;//year修改为2022
int age = 10;
int height = 30;
//const修饰的是其右边的内容
const int *p1 = &age;//p1不是常量,*p1是常量
int const *p2 = &age;//同上
//*p1 = 20;//*p1不能修改,报错
//p1 = &height;//
//*p1 = 40;//报错
int * const p3 = &age;//p3是常量,*p3不是常量
//*p3 = 20;//age=20
//p3 = &height;//p3不能修改,报错
//*p3 = 40;//height=40
const int * const p4 = &age;//第一个const修饰*p4,第二个const修饰p4,都是常量
int const * const p5 = &age;//同上
getchar();
return 0;
}
C++_const常量
最新推荐文章于 2025-02-05 11:23:09 发布