修饰变量和指针
-
const修饰普通类型的变量,告诉编译器某值是保持不变的。
-
const 修饰指针变量,根据const出现的位置和出现的次数分为三种
-
指向常量的指针(常量指针):指针指向一个常量对象,目的是防止使用该指针来修改指向的值。
-
指针常量:将指针本身声明为常量,这样可以防止改变指针指向的位置。
-
指向常量的常指针:一个常量指针指向一个常量对象。
#include <iostream>
using namespace std;
int main()
{
const int A = 10;//(1)const 修饰普通变量
//A = 20;A 是read-only
//cout<<A<<endl;
int arr[10] = {
0};
int arr1[10] = {
0};
const int* B = arr;//(2)const修饰常量指针
//*B = 10;//error: *B是 read-only,不能修改B指向地址的变量的值
B = arr1;//可以改变指针B指向的地址
cout<<*B<<endl;
/*int *C = arr;//不加const就能修改
*C = 10;
cout<<*C<<endl;*/
int* const D = arr;//(3)const修饰指针常量,此时不能改的是指针指的地址
*D = 10;//可以改值
//D = arr;//error:assignment of read-only variable ‘D’
cout<<*D<<endl;
const int* const E = arr;//(4)显然非常霸道,啥都不能改
//*E = 20;//error: assignment of read-only location ‘*(const int*)E’
//E = arr1;//error: assignment of read-only variable ‘E’
return 0;
}
修饰参数
- 值传递的 const 修饰传递,一般这种情况不需要 const 修饰
- 当 const 参数为指针时,可以防止指针被意外篡改。
*自定义类型的参数传递,需要临时对象复制参数,对于临时对象的构造,需要调用构造函数,比较浪费时间,因此我们采取 const 外加引用传递的方法。
const修饰成员函数
const 修饰类成员函数,其目的是防止成员函数修改被调用对象的值,如果我们不想修改一个调用对象的值,所有的成员函数都应当声明为 const 成员函数。
const在函数中三个位置
//修饰返回值
const int func(void);
//修饰参数,说明不希望参数在函数体内被修改
int func(const int i);
//修饰成员函数,其目的是防止成员函数修改被调用对象的值
int func(void) const;
例题
const int *a, int const *a, const int a, int *const a, const int *const a分别是什么,有什么特点。
1. const int a; //指的是a是一个常量,不允许修改。
2. const int *a; //a指针所指向的内存里的值不变,即(*a)不变
3. int const *a; //同const int *a;
4. int *const a; //a指针所指向的内存地址不变,即a不变
5. const int *const a; //都不变,即(*a)不变,a也不变