(1)定义普通变量的时候,只能初始化一次,以后不可再修改其值。
#include<iostream>
using namespace std;
int main()
{
//(1)在定义普通变量时,只能初始化一次,以后不能修改其值。
const int number = 100;
//number = 50; //会报错不可以修改
return 0;
}
2. const修饰函数参数
(2)在函数形参声明中,使用const,可以防止传进来的参数被修改。
#include<iostream>
using namespace std;
//(2)在函数参数中声明的变量,可以防止传进来的参数被修改。
void test(const int a)
{
//a = 10; //会报错不可以修改
cout << "a == " << a << endl;
}
int main()
{
test(200);
return 0;
}
3. const修饰类中成员函数
(3)在类中使用const定义的函数,在函数内部不能修改成员变量的值,但是可以修改传进来的形参值,但是一般不这么用。
#include<iostream>
using namespace std;
class MM
{
public:
MM();
~MM();
void my_ptintf(int b)const;
private:
int age = 18;
string name = "baby";
};
//(3)在类中使用const定义的函数,不能修改类中的成员变量,但是可以修改传进来的形参值
void MM::my_ptintf(int b)const
{
//age = 100; //会报错不可以修改类中的成员变量
}
int main()
{
my_ptintf();
return 0;
}
4. const修饰指针
const修饰指针有三种情况
-
const修饰指针 --- 常量指针
-
const修饰常量 --- 指针常量
-
const即修饰指针,又修饰常量
#include<iostream>
using namespace std;
int main() {
int a = 10;
int b = 10;
//const修饰的是指针,指针指向可以改,指针指向的值不可以更改
const int * p1 = &a;
p1 = &b; //正确
//*p1 = 100; 报错
//const修饰的是常量,指针指向不可以改,指针指向的值可以更改
int * const p2 = &a;
//p2 = &b; //错误
*p2 = 100; //正确
//const既修饰指针又修饰常量,指针的指向和指针指向的值都不可以修改
const int * const p3 = &a;
//p3 = &b; //错误
//*p3 = 100; //错误
system("pause");
return 0;
}
技巧:看const右侧紧跟着的是指针还是常量, 是指针就是常量指针,是常量就是指针常量