您的位置:首页 > 编程语言 > C语言/C++

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

2017-10-12 14:37 239 查看
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:
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux C/C++ const