常量和常函数

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
class B{
public:
int i;
int j;
int k;
void myPrintf(){
cout << "打印" << endl;
}

// 常函数,修饰的是this的内容,即是常量指针
// 不能在函数中修改this指向的变量的内容,使函数更加安全;
// const B* const this
void testConst()const{
//this->i = 10;
}

// B* const this
void testConst2(){
this->j = 10;
// this 是指针常量,不能修改指向
//this = (B*)0x00009;
}
};

void main(){
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;

// C/C++内存分区:栈、堆、全局(静态、全局)、常量区(字符串)、程序代码区
// 普通类属性与结构体中的属性有相同的内存布局(各属性大小的和),
// 静态成员存在于全局区中;
// 函数存在于程序代码区中;

// 普通对象能调用常函数
B b;
b.testConst();
b.testConst2();

const B b1;
// 常量对象只能调用常函数
// 在常函数中,当前对象指向的变量内容不能被修改,能够起到防止数据成员被非法访问
//b1.testConst2();

system("pause");
}