C/C++ const关键字的理解

2023-06-20,,

const 放在*前 是对变量(指针指向的空间 *p)进行修饰:指针指向的变量为const,即不能通过该指针来修改变量

const放在*后 是对指针本身的的修饰    :指针本身的指向不能改变,只能指向这个变量

const int p;      // p  为常量,初始化后不可更改
const int* p;     // *p 为常量,不能通过*p改变它指向的内容 
int const* p;     // *p 为常量,同上

int* const p;     // p  为常量,初始化后不能再指向其它内容

在C++中可以在的成员函数可以通过const来修饰。此时const修饰的是this指针变量本身,所以意味着当前成员函数不可以修改当前对象的成员函数.

class C1
{
public:
   int m_i;
   int m_j;
   const void m_method(int i,int j){
       m_i = i + 1;// error 不能修改this指针指向的属性
   }
   void const m_method1(int i,int j){
       m_i = i + 1;// error 不能修改this指针指向的属性
   }
   void m_method3(int i,int j) const{
       m_i = i + 1;// error 不能修改this指针指向的属性
   }
protected:
private:
};

《C/C++ const关键字的理解.doc》

下载本文的Word格式文档,以方便收藏与打印。