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


    const修饰的常函数

    常函数

    • 成员函数后加const,称为常函数。
    • 常函数内部不可以修改成员变量。
    • 常函数内可以改变加了mutable修饰的成员变量。
    code:
    	#include 
    	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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    常对象

    • 在声明对象前加const,常对象,常对象的内容不可以修改。
    • 常对象只能调用常函数。
    • 常对象可以修改mutable修饰的成员变量。
    code:
    	#include 
    	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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
  • 相关阅读:
    解决IDEA中Tomcat控制台乱码问题(包括sout输出乱码)
    Ubuntu20.4安装QT6
    微服务实战之领域事件
    MYSQL-GAP&插入意向锁 死锁记录
    笔记本电脑没有麦克风,声音无法找到输入设备
    隔离放大器
    STM32F4-ADC-常规通道-转换模式配置-总结
    Kafka详解(一)
    (Matalb分类预测)WOA-BP鲸鱼算法优化BP神经网络的多维分类预测
    vue init webpack xxx报错timeout
  • 原文地址:https://blog.csdn.net/weixin_48668114/article/details/132787530