目录
前言
this指针是c++里的一个关键字,一个对象的this指针不是对象的一部分,this指针是在访问非静态成员变量时编译器自动生成的,this的作用域是在类的内部。
this指针
是c++里的一个关键字,也是一个const指针,他指向对象本身。this指针是隐含于每一个非静态成员函数内的一种指针,this指针不需要定义,是编译器自动生成的,直接使用即可。
指针类型:const类型,即成员函数中不能给this指针本身赋值。
this指针存储在栈上。
this指针的使用情景:
在类的非静态成员函数中返回类对象本身,可以直接使用 return *this;
当参数与成员变量名相同时,如果需要操作,可以写成:this->n=n;(这里两个n不一样,不能写成n=n;)
我们可以试着写一个类来调用打印其this指针:
class student{
public:
int age;
void print(){
cout << this << endl; //打印this指针
}
};
int main(){
student *pstu = new student;
pstu->print(); //调用函数打印类的this指针
cout << pstu << endl; //当前对象
}
可以看到this指针和当前对象的值是一样的,说明this指针指向当前对象。
代码示例
this指针的使用:
class student{
public:
void print(); //类中写函数申明
void Setname(char *name);
void Setage(int age);
void Setscore(int score);
void show();
private:
char *name;
int age;
int score;
};
void student::print(){ //在外面写函数内容,这样写更整洁
cout <<"This:"<< this << endl;
}
void student::Setage(int age){
this->age = age; //因为形参名称和成员变量名称相同,所以用this以区别
}
void student::Setname(char *name){
this->name = name;
}
void student::Setscore(int score){
this->score = score;
}
void student::show(){
cout << "name:" << this->name << endl;
cout << "age:"<<this->age<< endl;
cout <<"score:"<<this->score << endl;
}
int main(){
student *pstu = new student;
pstu->Setname("张三");
pstu->Setage(20);
pstu->Setscore(99);
pstu->show();
return 0;
}