this指针

如果类的成员函数中涉及多个对象,在这种情况下需要使用this指针。

#include<iostream>
using namespace std;
class CBoy {
public:
	string m_xm;
	CBoy() { m_xm.clear(); cout << "调用了CBoy()构造函数。\n"; }
	CBoy(string xm) { m_xm = xm; cout << "调用了CBoy(string xm)构造函数\n"; }
	CBoy(const CBoy& bb) { m_xm = bb.m_xm; cout << "调用了CBoy(const CBoy& bb)拷贝构造函数\n"; }



};
class CGirl
{
public:
	string m_name;
	int m_yz;
	CGirl(const string& name, int yz) {
		m_name = name;
		m_yz = yz;
	}
	void show() const {
		cout << "I'm :" << m_name << ",the most beautiful gril." << endl;
	}
	const CGirl& pk(const CGirl g) {
		if (g.m_yz > m_yz)return g;
		return *this;
	}

};

int main() {
	CGirl g1("zhongge", 1), g2("ouge", 3);
	const CGirl& g3 = g1.pk(g2);
	g3.show();
	return 0;
}
I'm :ouge,the most beautiful gril.

C:\Users\代伟业\Desktop\C++\初始化列表\this指针\x64\Debug\this指针.exe (进程 10876)已退出,代码为 0。
按任意键关闭此窗口. . .

4个人比呢。

#include<iostream>
using namespace std;
class CBoy {
public:
	string m_xm;
	CBoy() { m_xm.clear(); cout << "调用了CBoy()构造函数。\n"; }
	CBoy(string xm) { m_xm = xm; cout << "调用了CBoy(string xm)构造函数\n"; }
	CBoy(const CBoy& bb) { m_xm = bb.m_xm; cout << "调用了CBoy(const CBoy& bb)拷贝构造函数\n"; }



};
class CGirl
{
public:
	string m_name;
	int m_yz;
	CGirl(const string& name, int yz) {
		m_name = name;
		m_yz = yz;
	}
	void show() const {
		cout << "I'm :" << m_name << ",the most beautiful gril." << endl;
	}
	const CGirl& pk(const CGirl &g)const {
		if (g.m_yz > m_yz)return g;
		return *this;
	}

};

int main() {
	CGirl g1("zhongge", 1), g2("ouge", 3),g3("zhuge",8),g4("linzengyu",9 );
	const CGirl& g = g1.pk(g2).pk(g3).pk(g4);
	g.show();
	return 0;
}
I'm :linzengyu,the most beautiful gril.

C:\Users\代伟业\Desktop\C++\初始化列表\this指针\x64\Debug\this指针.exe (进程 5088)已退出,代码为 0。
按任意键关闭此窗口. . .

每个成员函数都有一个this指针,可以用它访问调用者对象的成员。(可以解决成员变量名与函数形参名相同的问题)

class CGirl
{
public:
	int aa;
	void function(int aa) {
		this->aa = aa;
	}
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值