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;
}
结果: