const的使用有用来修饰变量,修饰指针和修饰引用,接下来我们将一一进行解释和代码测试。
核心:const用来修饰变量时,使得变量的值不能再改变。
所以我们在学习const的用法时,最关键的就是要确定const到底修饰的哪个东西(主要是在const修饰指针时),然后思考哪个部分不可以被改变就可以了。其实,通过这样的思考路径,const是很容易学习的。
const 修饰变量:
#include <iostream>
using namespace std;
int main() {
cout << "本程序目的在于测试const的用法。" << endl;
cout << "第一部分,const用于修饰变量时:" << endl;
int x=3;
const int y=5;
x=6,y=7;
cout << "当我们想要改变常量变量的值时,能够编译成功吗?" << endl;
return 0;
}
结果如图所示:
Scanning dependencies of target const
[ 50%] Building CXX object CMakeFiles/const.dir/main.cpp.o
/Users/cprimer/CLionProjects/const/main.cpp:9:10: error: cannot assign to variable 'y' with const-qualified type 'const int'
x=6,y=7;
~^
/Users/cprimer/CLionProjects/const/main.cpp:8:15: note: variable 'y' declared const here
const int y=5;
~~~~~~~~~~^~~
1 error generated.
可以看出,在想要给已经由const修饰过的变量进行赋值时,系统会报错。
const修饰指针时:
const int*p=&x;//等价于 int const *p, 注意这两种表达中const修饰的都是*p这个变量,而*p代表的是什么呢?代表的是指针所指变量的值,也就是说我们不能通过*p来改变其所指变量的值,但是我们无权确定其所指变量是否是一个常量。
int* const q=&x;//由此定义我们可以看出,const修饰的是指针q,q在指针中代表的是一个指针的指向,所以q指针的指向无法改变。
p=&y;//q=&y;这种语法是错误的,因为q是由const修饰的。 *q=11;//*p=11;这种语法是错误的,因为*p是由const所修饰。
还有一点要注意的是:
const int a=5;
int *p=&a;//这句代码是错误的,因为a是一个常量,是无法被改变的。但是如果该语句成立,便可以由*p进行修改a的值,很明显是错误的。
运行代码如下:
#include <iostream>
using namespace std;
int main() {
cout << "本程序目的在于测试const的用法。" << endl;
//cout << "第一部分,const用于修饰变量时:" << endl;
int x=3;
const int y=5;
cout << "第二部分,const用于修饰指针时:" << endl;
const int*p=&x;//等价于 int const *p, 注意这两种表达中const修饰的都是*p这个变量,而*p代表的是什么呢?代表的是指针所指变量的值,也就是说我们不能通过*p来改变其所指变量的值,但是我们无权确定其所指变量是否是一个常量。
int* const q=&x;//由此定义我们可以看出,const修饰的是指针q,q在指针中代表的是一个指针的指向,所以q指针的指向无法改变。
cout<<*p<<","<<*q<<endl;
p=&y;//q=&y;这种语法是错误的,因为q是由const修饰的。
*q=11;//*p=11;这种语法是错误的,因为*p是由const所修饰。
cout<<*p<<","<<*q<<endl;
return 0;
}
运行结果如图所示:
本程序目的在于测试const的用法。
第二部分,const用于修饰指针时:
3,3
5,11
进程已结束,退出代码 0
const修饰引用时:
const int &a=x;//const修饰的是&a,也就是说我们无法改变引用的值,也就是说无法通过引用a来改变x的值,
a=6;//语法错误,无法通过常量引用来改变变量的值。
在常量引用的方面,我们需要注意的一点就是常量引用作为函数的形参时,在函数内部改变产量引用形参是无法改变实参的值的,所以会产生错误(函数内部一旦发生改变常量引用形参的值的时候)。
例如:
void fun(const int &a,const int &b){
a=10;
b=20;
}
当你调用fun(x,y)时,一定会产生错误。
Scanning dependencies of target const
[ 50%] Building CXX object CMakeFiles/const.dir/main.cpp.o
/Users/cprimer/CLionProjects/const/main.cpp:23:6: error: cannot assign to variable 'a' with const-qualified type 'const int &'
a=10;
~^
/Users/cprimer/CLionProjects/const/main.cpp:22:21: note: variable 'a' declared const here
void fun(const int &a,const int &b){
~~~~~~~~~~~^
/Users/cprimer/CLionProjects/const/main.cpp:24:6: error: cannot assign to variable 'b' with const-qualified type 'const int &'
b=20;
~^
/Users/cprimer/CLionProjects/const/main.cpp:22:34: note: variable 'b' declared const here
void fun(const int &a,const int &b){
~~~~~~~~~~~^
2 errors generated.