- const修饰函数
目的是防止函数修改对象的数据成员,因此在const修饰的函数中不允许调用非const函数,因为非const函数可能会修改对象的数据成员。
#include <iostream>
class Test {
public:
void set(int _a) {
a = _a;
}
void output() const {
//a = 5; 编译错误
//cannot assign to non-static data member within const member function 'output'
printf("%d\n", a);
}
private:
int a;
};
int main() {
Test test;
test.set(10);
test.output();
return 0;
}
- 修饰函数参数
const用来修饰函数参数,如果修饰的参数为按值传參,那么传入的参数不可以被修改,实际上意义并不是太大,如果参数为指针的时候,那么传入将会是实参,为了保证实参的值不会受到影响使用const进行保护,使得在函数体内不会改变实参的数据。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string.h>
const int MAX_DATA_SIZE = 1024;
void fun(const char * src, char * s) {
//strcpy(src, s); 编译错误
}
int main() {
char a[MAX_DATA_SIZE] = "--------", b[MAX_DATA_SIZE] = "**********";
fun();
return 0;
}
注:const指针可以接受非const指针参数,但是非const指针不能接受const指针参数。
3. 常量指针
常量指针可以理解为指向常量的指针变量写法为
const int * p;
我们可以理解为 **p is a pointer to const int(从后向前读)**即为p是一个指针指向常量int,接下来我们用代码演示一下
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string.h>
const int MAX_DATA_SIZE = 1024;
int main() {
int a = 5, b = 6;
const int * p = &a;
*p = b;// 编译错误
p = &b;
return 0;
}
- 指针常量
与常量指针不同,指针常量的本质就是个常量不可改变,只是用指针来修饰它,后来不可修改,但是他指向的值可以修改。
写法为:
int * const p;
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string.h>
const int MAX_DATA_SIZE = 1024;
int main() {
int a = 5, b = 6;
int * const p = &a;
*p = b;
p = &b; //编译错误
return 0;
}