this指针介绍
1.this 指针是 C++实现封装的一 种机制,它将对象和该对象调用的成员函数连接在一起,在外部看来,每一个对象 都拥有自己的函数成员。每个对象用有独立的数据。每个对象共享同一个方法。this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。当前对象指正在使用的对象。如:ob.show(),ob就是当前对象,this就指向ob。
成员函数的参数和成员变量重名,this区分
代码演示:
#include <iostream>
using namespace std;
class Person
{
private:
char *name;
int age;
float score;
public:
Person(char *name,int age,float score)
{
this->name=name;
this->age=age;
this->score=score;
}
void show(void)
{
cout<<this->name<<"的年龄:"<<this->age<<",成绩:"<<this->score<<endl;
}
};
int main(int argc, char *argv[])
{
Person ob1("小明",16,99.6);
ob1.show();
return 0;
}
注:成员变量和成员函数的形参同名,如果写作name =
name;这样的语句,就是给形参name赋值,而不是给成员变量name赋值。而写作this -> name =
name;后,=左边的name就是成员变量,右边的name就是形参,一目了然。
在类的普通成员函数中返回对象本身
代码演示:
#include <iostream>
using namespace std;
class Data
{
public:
Data& data(char *pt)
{
cout<<pt;
return *this;
}
};
int main()
{
Data pn;
/*方法1:
pn.Data("xxx");
pn.Data("ssss");
pn.Data("dddd");*/
//方法2:
pn.data("xxx").data("ssss").data("dddd");
return 0;
}
注:this是什么?
1.this 实际上是成员函数的一个形参,在调用成员函数时将对象的地址作为实参传递给 this。不过 this 这个形参是隐式的,它并不出现在代码中,而是在编译阶段由编译器默默地将它添加到参数列表中。
2.this 作为隐式形参,本质上是成员函数的局部变量,所以只能用在成员函数的内部,并且只有在通过对象调用成员函数时才给 this 赋值。