1、const int max = 100;
定义const常量,不能修改max的值。
2、const int max = 100; int min = 10 ;
const int& ma = max; const int& mi = min;
定义常量引用,不能通过引用修改变量的值, 所指向的变量可以不是const常量。
3、const int max = 100; int min = 10 ;
const int* pMax = &max; const int* pMin = &min; pMax = &min ;
定义常量指针,不能通过指针修改变量的值,但可以修改指针所指向的地址,所指向的变量可以不是const常量。
备:const int* pMax 和 intconst* pMax 一样
4、int max = 100;
int * const pMax = &max; *pMax = 900 ;
定义指针常量,指针pMax是常量,不能修改所指向的地址,但可以修改所指向变量的值。
5、int max = 100;
const int* const pMax = &max
定义指向常量的指针常量。即3和4的合体。
备:注意指针常量与常量指针的区别,一个修饰指针本身,一个修饰指针所指向的变量。
6、constexpr和常量表达式
常量表达式(const expression)是指值不会改变并且在编译过程中就能得到计算结果的表达式。
C++11新标准规定,允许将变量声明为constexpr类型以便由编译器验证变量的值是否是一个常量表达式。
主要const 和 constexpr的区别:
const int *p = nullptr; 常量指针
constexpr int * q = nullptr 指针常量。
7、void foo(const char* var)、void foo(const int& var)
修饰参数表示函数体中不能修改参数的值。
8、const int foo()、 const int* foo()
返回值是常量。
9、void foo() const
修饰成员函数,表示不能修改成员变量,也不能调用类中任何非const成员函数。