C++-链式调用const成员函数

本文探讨了如何在类A中定义const和非const版本的print成员函数,以及为何底层const的print可以重载。通过实例讲解了const对象调用规则和成员函数隐式this指针的作用。

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

假设定义了一个类A,A包含一个int类型的数据成员n、print成员函数和set成员函数,print成员函数打印n值,set成员函数改变n值。由于print不会改变数据成员,因此应声明为const成员,另外又因为是const成员,所以隐式传入的this指针是const A *类型,返回引用是为了方便链式调用,此时*this是const A 类型,所以返回值是const A &类型,代码如下:

class A {
	int i = 0;
public:
	const A &print() const {
		cout << i<<endl;
		cout << "const";
		return *this;
	}

	A & set(int n) {
		i = n;
		return *this;
	}
};

当我们使用如下代码:

int main() {
	A a;
	a.print().set(7);
}

会发生报错,因为print返回的是const A &类型,而const对象无法调用非const成员函数,也无法修改const对象数据成员。

解决方法是重载print函数

class A {
	int i = 0;
public:
	const A &print() const {
		cout << i<<endl;
		cout << "const";
		return *this;
	}
	A &print() {
		cout << i << endl;;
		cout << "non-const";
		return *this;
	}

	A & set(int n) {
		i = n;
		return *this;
	}
};

const A &是底层const,因此print可以成功重载(顶层const无法重载)。对const版本的print来说,隐式传入的this指针是const A * 类型,而非const版本的print函数隐式传入的是A *类型,根据最佳匹配原则,如果是A类型的对象调用print,将调用非const版本,因为相比const版本,this指针不需要进行类型转换,此时返回值是非常量因此可以调用set函数;如果是const A类型的对象调用print,将调用const版本print,因为const A *无法转换为A *,唯一匹配的是const版本print。

知识点:

1.底层const可以重载,顶层const无法重载

2.成员函数调用时隐式传入this指针,指向调用的对象

3.const对象只能调用const成员函数;const对象的值不能被修改,在const成员函数中修改const对象数据成员的值是语法错误;在const函数中调用非const成员函数是语法错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

mrbone11

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

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

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

打赏作者

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

抵扣说明:

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

余额充值