C/C++之const

176 阅读2分钟

const代表常量的意思,使用const修饰的值不能改变

修饰左值(修饰全局变量、修饰局部变量、修饰成员变量、修饰函数参数)

#include <iostream>
using namespace std;

const int i_1 = 99;	//修饰全局变量

void test(const int value){
	//value++;		//报错,不能修改	
}

int main()
{
	const int i_2 = 666;	//修饰局部变量
	//i_1++;		//报错,不能修改
	//i_2++;		//报错,不能修改
	
	test(100);
   return 0;
}

修饰成员函数

#include <iostream>
using namespace std;

class MyClass {
public:
	MyClass() : value(0){}
	void Test() const {
		int i = 300;
		i++;			//可以修改

		value++;		//报错,不能修改
	}
private:
	int value;
};

int main()
{
	MyClass myclass;
	//myclass.Test();

	return 0;
}

指针常量和常量指针

指针常量是指指针指向的值是常量,但是可以指向不同的指针,const在的左边,比如const int ptr

常量指针是指指针本身是常量,但是指针指向的值可以改变,const在的右边,比如int const ptr,不能写成int* ptr const

#include <iostream>
using namespace std;

int main()
{
	int i = 99;
	int j = 666;
	const int* ptr_1 = &i;		//这是指针常量
	//ptr_1 = &j;		//这是正常的
	//*ptr_1 = j;		//报错
	
	int x = 123;
	int y = 987;
	int* const ptr_2 = &x;		//这是常量指针
	//ptr_2 = &y;		//报错
	*ptr_2 = y;		//这是正常的
   return 0;
}

上面是只加一个const,还可以两个const修饰指针,比如const int* const ptr,代码例子如下

#include <iostream>
using namespace std;

int main()
{
	int i = 99;
	int j = 666;
	const int* const ptr_1 = &i;
	//下面两个都是不允许的
	//ptr_1 = &j;
	//*ptr_1 = j;
	
   return 0;
}

修饰数组的话,数组里面每个元素不可改变,比如,const int a[],那么数组里面每个元素类型是const int

#include <iostream>
using namespace std;

int main()
{
	const int a[] = {1, 2, 3, 4, 5};
	a[0] = 100;		//报错
   return 0;
}

提问一下,const int a = 100 的a真的不能改变吗?

#include <iostream>
using namespace std;

int main()
{
	const int a = 100;
	int* p = &a;
	*p = 666;
	cout << "a = " << a << endl;
   //cout << "Hello World";
   return 0;
}

总结

1、修饰左值,那么该值变为常量(不懂左值的需要去了解左值概念),这里值修饰全局变量、修饰局部变量、修饰成员变量、修饰函数参数

2、修饰成员函数,成员函数里面不能修改对象的值,可以更改不是对象的值数据

3、区分清楚指针常量和常量指针以及加两个const修饰指针的情况

4、修饰数组,数组里面的每个元素不能更改