const修饰变量

const 修饰的常量

const int aa = 100;
aa = 200;                     //error: assignment of read-only variable ‘aa’

const 修饰引用

const int &bb = aa;
bb = 200;                     //error: assignment of read-only reference ‘bb’

const 修饰指针

int a = 100;
int b = 200;

const int *p1 = &a;
*p1 = 200;                    //error: assignment of read-only location ‘* p1’
p1 = &b;

int * const p2 = &a;
*p2 = 200;
p2 = &b;                      //error: assignment of read-only variable ‘p2’

const int * const p3 = &a;
*p3 = 200;                    //error: assignment of read-only location ‘*(const int*)p3’
p3 = &b;                      //error: assignment of read-only variable ‘p3’

const修饰函数参数和返回值

修饰的函数参数一般是指针或者引用类型, 值传递使用const没什么实际意义.

void function1(const int *aa){
	*aa = 200;			//error: assignment of read-only location ‘* aa’
}

void function2(const int &aa){
	aa = 200;			//error: assignment of read-only reference ‘aa’
}

修饰返回值时一般是指针类型,表明返回指针的内容不可修改.

const int * function3(){}

const修饰类

  • const修饰类的成员属性,表示成员常量,不能被修改,且只能在初始化列表中赋值, 如下例的m_aa
  • const修饰类的成员方法, 则该方法不能修改类的成员属性, 不能调用类的非const成员方法.
  • const修饰类对象/指针/引用, 只能调用const修饰的方法, 不能修改成员属性.
class test
{
public:
	test():m_aa(100){}
	void func(){}
	void func1()
	{
		std::cout << "func1" << std::endl;	
	}
	void func1() const
	{
		std::cout << "func2 const" << std::endl;	
		m_bb = 20;					//error: assignment of member ‘test::m_bb’ in read-only object
		func();						//error: passing ‘const test’ as ‘this’ argument of ‘void test::func()’ discards qualifiers [-fpermissive]
	}
	const int m_aa;
	int m_bb;
};

int main()
{
	test t1;
	t1.func1();						//func1

	const test &t2 = t1;
	t2.func1();						//func2 const
	t2.m_bb = 100;						//error: assignment of member ‘test::m_bb’ in read-only object
}