C++系列-const修饰的常函数

const修饰的常函数

常函数

  • 成员函数后加const,称为常函数。
  • 常函数内部不可以修改成员变量。
  • 常函数内可以改变加了mutable修饰的成员变量。
code:
	#include <iostream>
	using namespace std;
	class Horse
	{
	public:
		int age = 3;
		mutable string color = "white";
		//this 指针是一个指针常量, Horse * const this, 它指向的地址不可以修改, const Horse * const this, 则表示其空间的内容也不能修改
		void show_age() const		//常函数,const其实是用来修饰this指针的,表示this指向的内存空间的内容也不可以修改
		{
			//age = 5;				// 常函数中不能修改普通成员变量
			color = "black";		// 当成员变量被mutable修饰后,常函数中可以修改
			cout << "it is " << age << endl;
		}
	};
	
	int main()
	{
		Horse horse1;
		horse1.show_age();
		system("pause");
		return 0;
	}
result:
	it is 3

常对象

  • 在声明对象前加const,常对象,常对象的内容不可以修改。
  • 常对象只能调用常函数。
  • 常对象可以修改mutable修饰的成员变量。
code:
	#include <iostream>
	using namespace std;
	class Horse
	{
	public:
		int age = 3;
		mutable string color = "white";
		//this 指针是一个指针常量, Horse * const this, 它指向的地址不可以修改, const Horse * const this, 则表示其空间的内容也不能修改
		void show_info() const		//常函数,const其实是用来修饰this指针的,表示this指向的内存空间的内容也不可以修改
		{
			//age = 5;				// 常函数中不能修改普通成员变量
			color = "black";		// 当成员变量被mutable修饰后,常函数中可以修改
			cout << "it is " << age << endl;
		}
		void show_info_1()
		{
			//age = 5;				
			color = "black";
			cout << "it is " << age << endl;
		}
	};
	
	int main()
	{
		Horse horse1;
		horse1.show_info();
		const Horse horse2;			// 常对象内的内容不可以修改
		//horse2.age = 5;			// 常对象不能修改普通的成员变量
		horse2.color = "brown";		// 常对象可以修改mutable修饰的成员变量
		cout << horse2.age << endl;
		cout << horse2.color << endl;
		horse2.show_info();
		//horse2.show_info_1();		// 常对象不能调用普通的成员函数,因为普通成员函数可以修改成员变量的值,而常对象对应的成员变量是不可以修改的,冲突。
		system("pause");
		return 0;
	}
result:
	it is 3
	3
	brown
	it is 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值