如果类的成员函数中涉及多个对象,在这种情况下需要使用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;
}
};