| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
 本帖最后由 大神本人 于 2020-10-25 13:01 编辑  
 
1. 修饰基本类型 
const int a = 1; 
int const b = 2; 
这两种写法是等价的;都表示被修饰的基本类型的值是不可修改(immutable)的 
 
a++; 
b++; 
报错:annot assign to variable 'b' with const-qualified type 'const int' 
 
2. 修饰指针 
 
int a = 1; 
int b = 2; 
 
const int *pa1 = &a; // pa1 is a pointer to const (variable) 
*pa1 = 2; // this will cause a error: Read-only variable is not assignable 
pa1 = &b; // fine; since pa the pointer itslef is variable, which means pa can point to different address 
 
int const *pa2 = &a; // 同上,也是常量指针,指向的常量是不能修改的 
 
int *const pa3 = &a; // pa2 is a constant pointer, which means the pointer itself is immutable. 
*pa3 = 3; // change a to 3 
pa = &b; // error, because pa (the pointer) itself is immutable... 
 
还有一种情况,就是把两个结合起来 
const int *const pa4 = &a;  
这声明并初始化了一个指向常量的常指针(a constant pointer which points to a constant) 
 
3. 修饰函数形参(parameter) 
 
C++函数的形参,分为传值和传引用两种,其中传指针是特殊的传值操作(pass by value) 
 
-3.1 按值传递 
 
void foo(const var); 
保证了“在foo函数内部var变量是immutable的” 
 
-3.2 按指针传递 
void foo(const int*ptr); 
void foo(int const *ptr) 
void foo(const *int ptr); // 没有这种写法,写出来只是为了好看 
void foo(int *const ptr); 
 
其中下面两个写法是等价的 
void foo(const int *ptr); 
void foo(int const *ptr); 
都表示传入的指针所指向的常量是immutable的 
 
void foo(int *const ptr); 
表示这是一个常指针(constant pointer),即指针本身是一个immutable的常量 
 
-3.3 按引用传递 
void foo(const int &a); 
void foo(int const &a); 
不允许修改传入的参数本身(parameter is alias for argument) 
 
4. 修饰函数返回值 
 
类比前面,const修饰的东西就是constant的 
注意结合多种情况 
比如返回constant pointer还是pointer to constant 
 
const int* foo(); // 返回一个pointer to constant,用pointer to constant 接受 
用pointer to constant接受:const int *pa = foo(); //pa指向的地址表示的值是immutable的 
 
5. 修饰类成员函数 
const 修饰类成员函数,防止成员函数修改被调用对象的值(不会改变实例本身) 
 
class Demo { 
public: 
        Demo(){} 
        Demo(int _value): _value(value){} 
        void setValue(int value); 
        int getValue() const; 
private: 
        int _value; 
}; 
 
getValue的实现 
 
int getValue() const 
{ 
        // this-> value ++; 这句话会报错:Cannot assign to non-static data member within const member function 'getValue' 
        return this-> _value; 
} 
 
这个const只能写在类成员函数签名后面,普通函数是不行的 
 
总结起来,C++的const可以修饰变量和函数,被const修饰后变成constant的。特别注意指针常量和常量指针的区别 
指针常量:本身是一个常量,int *const ptr = nulltr; //声明一个指针常量(本身也是一个指针) 
常量指针:本身是一个指针,const int *ptr = nulltr; 或者 int const *ptr = nullptr; |   
 
 
 
 |