1.this指针的概念
this指针指向被调用的成员函数所属的对象。
2.this指针的作用
作用一:用于区分形参和成员变量。
作用二:在类的非静态成员函数中返回对象本身,return *this。
注:this指针不可以修改指针的指向。
作用一代码示例:
#include <iostream> //C++标准输入输出头文件
#include <string>
using namespace std;
class Person {
public:
int num;
void sum(int num)
{
//形参和成员变量相同 用this区分
this->num = num;
}
};
int main()
{
Person p;
p.sum(10);
cout << p.num << endl;
system("pause");
return 0;
}
作用二代码示例:
#include <iostream> //C++标准输入输出头文件
#include <string>
using namespace std;
class Person {
public:
int num = 0;
Person& sum(int num)
{
//形参和成员变量相同 用this区分
this->num += num;
return *this;
}
};
int main()
{
Person p;
//p.sum(10)返回成员对象所属的对象p
p.sum(10).sum(10).sum(10).sum(10).sum(10).sum(10);
cout << p.num << endl;
system("pause");
return 0;
}
、