this指针
-
this指针作用:
c++的数据和操作也是分开存储,并且每一个非内联成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用同一块代码。所以,用this指针表明哪个对象调用自己。
-
定义:
this指针指向被调用的成员函数所属的对象。
-
性质:
成员函数通过this指针即可知道操作的是那个对象的数据。This指针是一种隐含指针,它隐含于每个类的非静态成员函数中。This指针无需定义,直接使用即可。
注意:静态成员函数内部没有this指针,静态成员函数不能操作非静态成员变量。
-
应用1:
函数参数和成员同名,可用this指针解决。
#include<iostream>
using namespace std;
class Data {
public:
int a;
public:
Data(int a) {
this->a = a;
cout <<"this地址:" << this << endl;
}
};
void test()
{
Data ob(10);
cout << ob.a << endl;
cout <<"对象地址:" << &ob << endl;
}
int main()
{
test();
}

-
应用2:
用this指针表示链式结构。
#include<iostream>
using namespace std;
class Data {
public:
int a;
public:
Data &myprint(int a) {
cout << a << " "<<" "<<this<<endl;
return *this;//返回调用该成员函数的对象
}
};
void test()
{
//Data()是匿名对象
//myprint()返回的还是匿名对象Data(),所以可以被不断调用。
Data().myprint(10).myprint(20).myprint(30);
}
int main()
{
test();
}




















