目录
【this指针】(重要)
c++的封装性:将数据 和 方法 封装在一起
数据 和 方法 是分开存储。
每个对象 拥有独立的数据.每个对象 共享同一个方法。
1、this指针的引入
#include <iostream>
using namespace std;
class Data {
public:
int m_num;
void setNum(int num) {
m_num = num;
}
};
void test01() {
Data ob1;
ob1.setNum(10);
cout << "ob1.m_num = " << ob1.m_num << endl;
Data ob2;
ob2.setNum(20);
cout << "ob2.m_num = " << ob2.m_num << endl;
Data ob3;
ob3.setNum(30);
cout << "ob3.m_num = " << ob3.m_num << endl;
}
int main() {
test01();
return 0;
}
运行结果:
#include <iostream>
using namespace std;
class Data {
public:
int m_num;
void setNum(int num) {
// m_num = num;
this->m_num = num;
}
};
void test01() {
Data ob1;
ob1.setNum(10);
cout << "ob1.m_num = " << ob1.m_num << endl;
Data ob2;
ob2.setNum(20);
cout << "ob2.m_num = " << ob2.m_num << endl;
Data ob3;
ob3.setNum(30);
cout << "ob3.m_num = " << ob3.m_num << endl;
}
int main() {
test01();
return 0;
}
注意:
1、this指针是隐含在对象成员函数内的一种指针
2、成员函数通过this指针即可知道操作的是那个对象的数据
3、静态成员函数内部没有this指针,静态成员函数不能操作非静态成员变量
(静态成员函数 是属于类 函数内部 没有this指针)
2.【this指针的使用】
1、当形参和成员变量同名时,可用this指针来区分
class Data
{
public:
int num;
// 形参和成员名相同
void setNum(int num) {
// 形参num
// 成员num this->num
// num = num; // 就近原则,形参num赋值给形参num
this->num = num; // 将形参num赋值给对象中成员num
}
};
2、在类的普通成员函数中返回对象本身(*this)(重要)‘
#include <iostream>
using namespace std;
class MyCout {
public:
MyCout& myCout(char *str) {
cout << str;
return *this; // *this 代表就是当前调用该函数的对象
}
};
int main() {
MyCout ob;
/*
ob.myCout("hehe");
ob.myCout("haha");
ob.myCout("xixi");
*/
ob.myCout("hehe").myCout("haha").myCout("xixi"); // ob.myCout("hehe") == ob
return 0;
}
● 链式调用
支持链式调用的成员函数特点:
1、 返回值是当前类的引用
2、 return 后面是*this
#include <iostream>
#include <string>
using namespace std;
class Fish {
private:
string breed;
int weight;
public:
Fish(const string& b, int w) : breed(b), weight(w) {}
// Getter and Setter for breed
string getBreed() const {
return breed;
}
void setBreed(const string& b) {
breed = b;
}
// Getter and Setter for weight
int getWeight() const {
return weight;
}
void setWeight(int w) {
weight = w;
}
};
class Cat {
public:
Fish& eat(Fish& f) {
if (f.getBreed() == "秋刀鱼") {
cout << "无论多沉,我都爱吃。" << endl;
f.setWeight(0);
return f;
} else {
if (f.getWeight() > 200) {
cout << "吃鱼!" << endl;
f.setWeight(0);
return f;
} else {
cout << "鱼太轻了,我不吃。" << endl;
return f;
}
}
}
};
int main() {
Fish aodao("秋刀鱼", 180);
Fish otherFish("其他鱼", 220);
Cat cat;
Fish resultAodao = cat.eat(aodao);
cout << "Aodao's weight after eating: " << resultAodao.getWeight() << endl;
Fish resultOtherFish = cat.eat(otherFish);
cout << "Other fish's weight after eating: " << resultOtherFish.getWeight() << endl;
return 0;
}