c++ this指针

1、用途

        1、用于区别同一个类中,具有相同变量名的成员函数内形参成员变量。

        2、链式引用成员函数,即可以通过返回this指针,来得到一个与自身相同类型的对象,进而达到连续调用成员函数的目的。

        注:当定义的成员函数为引用函数形式时,返回的时初始化的对象本身,如果为一般形式(即只返回类本身),则会生成新的类对象,继续链式引用。

2、代码示例

        用途1:(一般会将成员变量写成中间部分大写的形式来区分,如:myage -> myAge)

#include <iostream>

using namespace std;

class Cat {
public:
	void add_weight(float weight) {
		this->weight = weight;
		cout << weight << endl;
	}
private:
	float weight = 10;
};

int main() {

	Cat cat;
	cat.add_weight(20.);

	system("pause");
	return 0;
}

        输出:20

        用途2:

#include <iostream>

using namespace std;

class Cat {
public:
	Cat lose_weight1(float weight) {
		wEight -= weight;
		return *this;
	}
	Cat& lose_weight2(float &weight) {
		wEight -= weight;
		return *this;
	}
	void show() {
		cout << "wEight :" << wEight << endl;
	}
private:
	float wEight = 40;
};

int main() {

	Cat cat;
	float dw = 10.;
	cat.lose_weight1(dw).lose_weight1(dw);
	cat.show();

	Cat cat2;
	cat2.lose_weight2(dw).lose_weight2(dw);
	cat2.show();

	system("pause");
	return 0;
}

结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值