const修饰的成员函数

const修饰的成员函数

问题:

哪里出现编译报错了, 如何修改?

class A
{
public:
	const int get1() const
	{
		a1 = 10;
		return a1;
	}

private: 
	int a1 = 0;
};
int main()
{

	A a;
	a.get1();
	return 0;
}

当时以为是a是一个非const对象,调用了const成员函数导致编译错误的。然后修改方案是增加一个int get1(){}的非常量函数重载。

分析:

1. 对于非static成员函数,都有一个隐含的this指针

在这里插入图片描述

2. 对于const成员函数,该const修饰的实际是this指针

在这里插入图片描述

3. const修饰的成员函数内部,不能够对成员变量进行修改;const修饰的对象,状态在创建后不能被修改

在这里插入图片描述

4. 由于this指针与const关键字的作用

  • const成员函数内不能修改成员变量
  • const成员函数内,不能调用非const的函数

非const修饰的成员函数T* const this不能被const成员函的const T* const this进行赋值,权限放大了

  • 非const对象、成员函数可以调用const修饰的成员函数
T* const this;
const T* const this_arg = this;

将一个没有被const修饰的this指针的值赋值给一个被const修饰的this指针,权限可以缩小。

5. mutable关键字,用于修饰类的成员变量,提供绕过了常量性的限制的一种例外机制

class B
{
public:
	B(int val)
		:b1(val)
	{}

	void set(int val)
	{
		b1 = val;
	}

	void set(int val) const
	{
		b1 = val;
	}
public:
	mutable int b1;
};

int main()
{
	const B b(10);
	b.set(100);

	cout << ++b.b1 << endl;
	return 0;
}

在这里插入图片描述

6. const_cast()类型转换消除常属性

class B
{
public:
	int b1;
};

int main()
{
	const B b;

	B* b2 = const_cast<B*>(&b);
	B& b3 = const_cast<B&>(b);

	b2->b1 = 100;
	b3.b1 = 0;
	
	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值