C++ 常函数 常对象 const

本文解释了C++中const关键字如何影响成员函数的this指针,强调了const修饰的函数和对象限制修改行为,以及mutable修饰成员变量的特例。通过实例展示了常对象只能调用const成员函数且不能直接修改数据,但可通过指针间接操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

this 指针的本质: Person * const this;

常函数

用 const 修饰成员函数时,const 修饰 this 指针指向的内存区域,成员函数体内不可以修改本类中的任何普通成员变量。

void show() const
{
}

//const Person const this;//限制了 this 指针

当成员变量类型符前用 mutable 修饰时例外。

mutable int m_A;

常对象

常对象只能调用 const 的成员函数

常对象可访问 const 或非 const 成员属性,不能修改,除非成员用 mutable 修饰。

案列

//const修饰成员函数
class Person{
public:
	Person(){
		this->mAge = 0;
		this->mID = 0;
	}
	//在函数括号后面加上const,修饰成员变量不可修改,除了mutable变量
	void sonmeOperate() const{
		//this->mAge = 200; //mAg e不可修改
		this->mID = 10;
	}
	void ShowPerson(){
		cout << "ID:" << mID << " mAge:" << mAge << endl;
	}
private:
	int mAge;
	mutable int mID;
};

int main(){

	Person person;
	person.sonmeOperate();
	person.ShowPerson();

	system("pause");
	return EXIT_SUCCESS;
}
////const修饰类对象
class Person{
public:
	Person(){
		this->mAge = 0;
		this->mID = 0;
	}
	void ChangePerson() const{
		mAge = 100;
		mID = 100;
	}
	void ShowPerson(){
        this->mAge = 1000;
		cout << "ID:" << this->mID << " Age:" << this->mAge << endl;
	}

public:
	int mAge;
	mutable int mID;
};

void test(){	
	const Person person;
	//1. 可访问数据成员
	cout << "Age:" << person.mAge << endl;
	//person.mAge = 300; //不可修改
	person.mID = 1001; //但是可以修改mutable修饰的成员变量
	
	//2. 只能访问const修饰的函数
	//person.ShowPerson();
	person.ChangePerson();
}

不能直接修改, 但是可以通过指针间接修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值