由于在c++中,数据与操作是分开存储的,其中多个同类型对象会共用一块代码,而要搞清楚这一块代码是是哪个对象调用的,c++为我们提供了特殊的指针:“this”,来解决这个问题
成员函数通过this指针即可知道操作的是哪个对象的数据。this是一种隐含指针,其无需定义,直接使用。
下面来看其具体使用方法:
1.函数形参和成员同名可以用this指针来解决
class Data1
{
public:
int a;
public:
Data1(int a)
{
this->a = a;
cout << this << endl;
}
};
此时this指针保存的是调用该成员函数的对象的地址
因此,当函数形参和成员同名可以用this指针来解决
2.用this来完成链式操作
{
public:
Data2& f(int* str)
{
cout << str << " ";
return *this;//返回调用该成员函数的的对象
}
};
const修饰成员函数
使用const修饰的成员函数时,const指针指向的内存区域,成员函数体内不可以修改本类的任何普通成员变量(除了mutable修饰除外)
class Data3
{
public:
int a;
int b;
mutable int c;
public:
Data3(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
void f(void) const
{
c = 100;
cout << a << " " << b << " " << c << endl;
}
};
int main()
{
Data3 ob1(10, 20, 30);
ob1.f();
return 0;
}
在此简单介绍了this指针以及其几种用法,希望对读者们有所帮助。