常函数与常变量

常函数

#include <iostream>
using namespace std;

class Fun {
	private:
		int m_age;
	public:
		void setAge(int age) const
		{
			m_age = age;
		}
};

int main() {
	Fun f1;
	f1.setAge(18);
	return 0;
}

上述代码编译会报错。

每一个成员函数都隐含着一个this指针 ,而this指针的本质是指针常量,即指针指向的内存空间地址不可改变。

//Fun * const this
		void setAge(int age) const
		{
			this->m_age = age;
		}

当我们将Fun * const this 改写为 const  Fun * const this 此时的指针this既是指针常量也是常量指针,它指向的内空间地址无法改变,同时指向的内存空间存储的数据也无法改变。这是便会出现一个新的问题,新加的const添加到哪里?void前不可加,因为这是函数返回值类型;函数名前不可加,因为这是函数名;小括号内不可加,因为这是形参列表。因此只能加载先括号后面,也就是下面的形式,因此我们要知道函数后面的const是用来修饰this指针的。

void setAge(int age) const

当我们在函数后加上 const的本质是给this指针加上const变成const Fun * const this

 常对象

#include <iostream>
using namespace std;

class Fun {
	private:
		int m_age;
	public:
		Fun(int age):m_age(age){};
		//Fun * const this
		void showAge() const
		{
			cout << "常函数\tage:" << m_age << endl;
		}
		
		void showAge1()
		{
			cout << "普通函数\tage:" << m_age << endl;
		}
};

int main() {
	const Fun f2(18);
	f2.showAge();
	f2.showAge1();
	return 0;
}

同样的,常对象的属性也是无法修改的,这里就不过多赘述。

在上述例子中,f2.showAge()的可以正常调用,因为该函数是常函数,因此不会存在改变对象成员属性的情况。但是,f2.showAge1()的不可以正常调用,编译时会报错,因为该函数不是常函数,就会有在函数内部改变对象成员函数的可能,这是不允许的,所以在编译时便会报错。

使用mutable 关键字修改const成员值

#include <iostream>
using namespace std;

class Fun {
	private:
		mutable int m_age;
	public:
		Fun(int age):m_age(age){};
		//Fun * const this
		void setAge(int age) const
		{
			m_age = age;
			cout << "常函数\tage:" << m_age << endl;
		}
		
		void set(int age)
		{
			m_age = age;
			cout << "普通函数\tage:" << m_age << endl;
		}
};

int main() {
	Fun f1(10);
	f1.set(11);
	f1.setAge(111);
	
	const Fun f2(20);
	f2.setAge(20);
//	f2.set(22);
	return 0;
}

虽然常对象和常函数无法修改成员变量的值,但也不是绝对的。

使用mutable修饰的成员变量,我们可以修改他的值。

例如上述对象f1,调用常函数时可以修改mutable修饰的变量。

常对象f2,也可以调用常函数修改mutable修饰的变量。切记,常对象只能调用常函数!

 

 

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起风了呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值