一、const的作用

在Java当中我们有final关键字用来定义一个常量,常量即固定了的变量定义之后是无法修改的即只读方式访问。在C++中也有这么一个关键字const。
const可以修饰的不仅仅是函数,变量,成员参数等还能用于指针。
使用的方法也很简单
定义一个const常量有两种格式
type const varname;
const type varne;
这两种格式区别就是关键字的位置不一样
比如下面代码

1
2
const int ming = 0;
int const ming2 = 1;

这两个方法定义的常量都是无法进行修改了的

二、const 和指针

const可以和指针一起使用如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <string>


namespace XiaoMing {
class Student {
private:
std::string name;
int age, score;

public:
static int total;
int test = 0;

std::string getName() const {
return name;
}

void setName(const std::string name) {
Student::name = name;
}

int getAge() const {
return age;
}

void setAge(int age) {
Student::age = age;
}

int getScore() const {
return score;
}

void setScore(int score) {
Student::score = score;
}

void static setTotal(int total) {
Student::total = total;
}

void show() {
std::string info;
std::cout << "姓名:" << this->getName() << std::endl
<< "年龄:" << this->getAge() << std::endl
<< "得分:" << this->getScore() << std::endl
<< "总人数:" << this->total << std::endl;
}

};

int XiaoMing::Student::total = 100;

}


int main() {
XiaoMing::Student *student = new XiaoMing::Student;

const XiaoMing::Student *student2 = new XiaoMing::Student;
XiaoMing::Student const *student3 = new XiaoMing::Student;
XiaoMing::Student *const student4 = new XiaoMing::Student;

student2->test = 10;
student3->test = 10;
student4->test = 10;



student2 = student3;
student3 = student4;
student4 = student2;

return 0;
}

上述代码所示,分别定义实例化了三个常量对象但是const的位置不一致,那么他们有什么区别呢?首先student2和student3两个二则并无区别只是const的位置不一致,但是他们都是用于修饰指针所指向的值的而不是这个常量本身。student3呢修饰的则是他本身。上面给三个对象所指向的值进行赋值发现前面两个编译器会报错但student4->test = 10;没有报错因为前两个所指向的值是只读的不能修改的student4是修饰当前的变量的。后面三行给常量赋值的时候前面两个没报错student4 = student2;却报错了因为student4是只读的前面两个只是所指向的值为只读但他们本身是可写的这就是他们两个的区别

大家可以这样来记忆:const 离变量名近就是用来修饰指针变量的,离变量名远就是用来修饰指针指向的数据,如果近的和远的都有,那么就同时修饰指针变量以及它指向的数据。

那么指针在什么情况下采用const呢?在我们传参的时候如果我们不希望函数对我们所指向的值进行修改只能读取的时候就可以用到啦!

三、const 和非 const 类型转换

const char 和char 是不同的类型,不能将const char 类型的数据赋值给char 类型的变量。但反过来是可以的,编译器允许将char 类型的数据赋值给const char 类型的变量。

1
2
3
4
5
const XiaoMing::Student *student2 = new XiaoMing::Student;
XiaoMing::Student const *student3 = new XiaoMing::Student;
XiaoMing::Student * student4 = new XiaoMing::Student;
student3 = student4;
student4 = student3;

上面student3 = student4;是允许的student4 = student3;是不允许的

四、常成员函数

const 成员函数可以使用类中的所有成员变量,但是不能修改它们的值,这种措施主要还是为了保护数据而设置的。const 成员函数也称为常成员函数。

函数开头的 const 用来修饰函数的返回值,表示返回值是 const 类型,也就是不能被修改,例如const char *
getname()。

函数头部的结尾加上 const 表示常成员函数,这种函数只能读取成员变量的值,而不能修改成员变量的值,例如char * getname()
const。