共享数据的保护const

1、常对象

const 类型名 对象名;
常对象必须进行初始化,而且不能被更新
/*例如 const A a(3,4) a 是常对象,不能被更新

const int n=10; //正确,用10对常量n进行初始化
n=20; //错误,不能对常量赋值;
*/

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
#include <iostream>
using namespace std;
class A{
public:
A(int i ,int j):x(i),y(j){};
private:
int x,y;
};
const A a(3,4); //a是常对象,不能被更新;
```
### 2、修饰类成员
类型说明符 函数名(参数表) const;
const是函数类型的一个组成部分,因此在函数的定义部分也要带const
``` bash
#include <iostream>
using namespace std;
class R{
public:
R(int r1,int r2):r1(r1),r2(r2){}
void print();
void print() const;
private:
int r1,r2;
};
void R::print()
{
cout<<r1<<";"<<r2<<endl;
}
void R::print() const
{
cout<<r1<<":"<<r2<<endl;
}
int main()
{
R a(5,4);
a.print(); //调用void print()
const R b(20,52);
b.print(); //调用void print() const
return 0;
}
/*
在R类中说明了两个同名函数print,其中一个是常函数
在主函数中定义了两个对象a与b,其中对象b是常对象。通过对象a调用的是没有用const修饰的函数
而通过b调用的是const修饰的常函数。
*/

Fork me on GitHub