关于const的一些理解
1. 常变量
申明一个常变量的时候必须理解给他初始化,不然后续就不能给该变量进行初始化,而且还会报错,比如如下代码。
const int t;
t = 0;
出错信息:
testConst.cpp:24:12: error: uninitialized const ‘t’ [-fpermissive]
const int t;
^
testConst.cpp:25:4: error: assignment of read-only variable ‘t’
t = 0;
2. 常引用
声明一个常引用也需要直接初始化,不然会报错。在引用初始化之后就不能更改引用的变量。但是 可以改变引用变量的值,如下
int a=0;
const int &t=a;
cout << t << endl;
a = 2;
cout << t << endl;
输出就为
0
2
3. 常指针
话不多说,直接上代码
▸ int a = 2;
▸ const int *t=&a; // 常指针,指向的地址可以改变,但是不能改变该地址的值
▸ cout << *t << endl;
▸ a = 3;
▸ cout << *t << endl;
▸ // *t = 5; // 出错error: assignment of read-only location ‘* t’
▸ int b=4;;
▸ t = &b;
▸ cout << *t << endl;
▸ int * const t1 = &a; // 指针常量,这个和常引用类似,不能改变指针的指向,但是可以改变指
向地址的值
▸ cout << *t1 << endl;
▸ *t1 = 6;
▸ cout << *t1 << endl;
▸ a = 7;
▸ cout << *t1 << endl;
▸ // t1 = &b; // 出错 error: assignment of read-only variable ‘t1’
▸ //
▸ const int* const t2 = &a; // 常指针常量,包含上面两个特性
▸ cout << *t2 << endl;
▸ a = 8;
▸ cout << *t2 << endl;
▸ // t2 = &b; // 出错error: assignment of read-only variable ‘t2’
▸ // *t2 = 9; // 出错error: assignment of read-only location ‘*(const int*)t2’
记忆方法:const int *
常指针,常量加在int
上的,所以可以改变指向。int * const
,指针常量,指针加在常量加在*
上,所以是指针常量。
4. 常函数
常函数是针对类的成员函数的,常函数中 只能调用常成员函数,否则会出错
代码原型:
class B {
▸ public:
▸ ▸ void test1() const {}
▸ ▸ void test2() const {
▸ ▸ ▸ A* t = new A;
▸ ▸ ▸ test3();
▸ ▸ ▸ test1();
▸ ▸ }
▸ ▸ void test3() {}
};
出错信息
testConst.cpp:17:10: error: passing ‘const B’ as ‘this’ argument discards qualifiers [-fpermissive]
test3();
^
testConst.cpp:20:8: note: in call to ‘void B::test3()’
void test3() {}