C/C++中const的基本特性

来源:互联网 发布:js onclick没反应 编辑:程序博客网 时间:2024/05/20 09:09

1、 const在C中是只读变量,在C++中是常量,c++编译器会为const常量新增一个符号表,防止通过地址修改这个const常量,而C编译器可以通过地址修改const修饰的值


2、 const修饰指针常量,放在*号的左边是修饰指针所指向的内容,放在*号右边是修饰指针本身

const int *a;<span style="white-space:pre"></span>//修饰指针所指向的内容,即这个指针指向的内容不可变int* const a; <span style="white-space:pre"></span>//修饰指针,即a不可变 


3、当函数传入的不需要修改时,我们应该用const修饰这个参数

char *strcpy(char *des, const char *source){char *tmp = des;assert((des != NULL) && (source != NULL));while ((*des++ = *source++) != '\0');return tmp;}

4、当一个类的成员函数被声明为const时,则这个成员函数不能修改类的数据成员,可以通过对类里面的数据成员加上mutable修饰,就可以修改该数据成员

class TestConst{public:TestConst(int i);~TestConst();int incr() const;int decr(); private:mutable int m_Count;//加mutable修饰};

TestConst::TestConst(int i) : m_Count(i){}TestConst::~TestConst(){}int TestConst::incr() const//类的数据成员需要加mutable修饰{return ++m_Count;}int TestConst::decr(){return --m_Count;}


0 0