定义
- 系统在创建对象时,默认生成的指向当前对象的指针。这样作的目的,就是为了带来方便
作用
1、避免构造器的入参与成员名相同
using namespace std;
class stu{
public:
stu(string name,int age){
this->name = name;
this->age = age;
}
void prin()
{
cout<<name<<age<<endl;
}
private:
string name;
int age;
};
int main ()
{
stu student("zhangxiang",22);
student.prin();
return 0;
}
2、基于 this 指针的自身引用还被广泛地应用于那些支持多重串联调用的函数中。比如连续赋值。
连续赋值:a=b=c=d;:
sstring &sstring::operator=(const sstring & another)
{
if(another._str==_str)
return *this; s4 = s4;
delete [] _str;
int len = strlen(another._str);
strcpy(_str,another._str);
return *this;
}
3、this其实是指向本类对象的常指针 stu * const this
- 注意下面两者的区别
- class * const this; //表示this指针不可被修改
- const class * this; //表示this指针指向的内存里面的内容不可被修改
Stu* const & growUp()
{
this->age++;
return this;
}