关于const
const 与 c 语言中的#define 相似,但const有语法,计算机可以检验出语法错误,#define则不行。因此,定义常量时,建议使用 const。
指针的const用法
指针指向const修饰的变量时,应该是const int const *p = &a;
#include<iostream>
#include<stdlib.h>
using namespace std;
int main(void){
//Pointer: *p
int x = 10;
int y = 12;
int const *p = &x;//const int *p = &x;
//*p = 12;cannot Rewrite
p = &y;//can pointer to another
int * const a = &x;
*a = 12;//cannot Rewrite
//a = &y;cannot pointer to another
const int * const m = &a;//int const *const m = &a;
//Can neither Rewrite nor pinter to another
cout << *p ;
cout << *a;
}
函数中的const不能对常量赋值
#include<iostream>
#include<stdlib.h>
using namespace std;
void fun(const int &a,const int &b) {
//if exist const, cannot assign a constant value
a = 10;
b = 20;
}
int main(void){
int x = 1;
int y = 2;
fun(x,y);
cout << x<< "," << y;
}
本文详细解析了C++中const关键字的多种用途,包括常量定义、指针与const结合使用、以及在函数参数中的应用。通过具体示例说明了const如何帮助提升代码质量和安全性。
1212

被折叠的 条评论
为什么被折叠?



