C++(三十三)之const成员函数和const 对象

我们前面学过const修饰的常指针,

在常指针定义的时候需要初始化,且后续不可以再改变。

 那么今天我们学习一下常成员函数和常对象。

常成员函数: 格式如下

void memFunc(void) const

常对象:

const Person *p = new Person();

语法很简单但是我们在使用的时候要注意:

常成员函数只能被调用,不能修改成员变量,除非成员变量有mutable关键字修饰。

而常对象只能调用常成员函数,因为常对象不能修改成员变量。

除非成员变量用mutable关键字修饰。

 

下面我们举例说明:

/****************************************************
 * brief  : const修饰成员函数和对象 
 * author : shao 
 * date   :	2020-03-06
 * note   : none
 *
 ****************************************************/
#include <iostream>

using namespace std;


class Person{
public:
	Person()
	{
		this->p_age = 0;
		this->p_ID  = 0; 
	} 
	 
 	/* const 修饰后不能修改
	 * 成员变量数据,除非该成员变量有mutable修饰 
	 */
	void operateData(void) const  
	{
		//this->p_age = 10;  //这行编译不能过,const成员不可修改成员变量 
		this->p_ID = 20;     //这行编译可以过,p_ID是mutable修饰的 
		//this->getNum = 30;   //静态变量也不可以修改 
		
		cout << "p_age = " << this->p_age << endl;
		cout << "p_ID = " << this->p_ID << endl;
		//cout << "getNum = " << getNum << endl;
	}
	
	int p_age;
	mutable int p_ID;
	static int getNum; 
}; 

void test01(void)
{
	Person *p = new Person();
	
	p->operateData();
} 


/*
 * 常对象只能调用常成员函数,
 * 如果想要修改成员变量,那么必须要是mutable修饰
 *  
 *   
 */
class NewPerson{
public:
	NewPerson()
	{
		this->p_age = 0;
		this->p_ID = 0;
	}
	
	//常成员函数 
	void setNewPerson(void) const
	{
		//this->p_age = 15;  //本行编译不过,常成员函数不能修改成员变量 
		this->p_ID = 25;   //本行成员变量有mutable修饰,可以编译通过 
	}
	
	void showInfo(void)
	{
		this->p_age = 35;
		
		cout << "NewPerson age: " << this->p_age << endl;
		cout << "NewPerson ID :" << this->p_ID << endl;
	} 

	int p_age;
	mutable int p_ID;
};

void test02(void)
{
	const NewPerson *np = new NewPerson();
	
	np->setNewPerson(); //常成员函数可以调用
//	np->showInfo();//不可以调用,因为普通成员函数可能会修改成员变量的值 
	np->p_ID = 36; //可以修改mutable 变量 
	
	//np->showInfo();  //这是常对象调用普通成员函数,不可以 
}

int main(void)
{
	test01();
	
	cout <<"========================华丽的分割线==================\n" << endl; 
	
	test02(); 
	
	return 0;
} 

运行结果如下:

 

test02中的常对象没法调用普通成员函数,因为普通成员函数有可能会修改变量。

这与const的初衷相违背,故只能有test01的内容被打印出来。 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值