C++const在结构体中的使用
基础知识
- 在用指针传参时,可能进行误操作,改变指针指向内存数据
- 解决办法:在参数调用时,参数前加入const修饰即可
测试源代码
/*
* 时间:2021.02.11
* 内容:const在结构体变量中使用
*/
/*
* const防止误操作:
* 在使用指针传参时,其值可能被改变(误操作)
* 为了避免这种情况的发生
* 在参数调用时,参数前加入const修饰
*/
#include <iostream>
using namespace std;
struct S
{
int a;
}s;
void show(const struct S*);
/*
* 此处加入const后
* 为常量指针即*p的值不能改变
*/
int main()
{
s = { 1 };
struct S* p = &s;
show(p);
system("pause");
return 0;
}
void show(const struct S* s)
{
cout << s->a << endl;
return;
}
// KEEP CALM AND CARRY ON