1.什么是this?
1.定义
在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址(指向本身)。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。
2.this作用域是在类内部,只能在成员函数中使用,并且只有在成员函数中才有定义
创建一个对象后,不能通过对象使用this指针。也无法知道一个对象的this指针的位置(只有在成员函数里才有this指针的位置)。当然,在成员函数里,你是可以知道this指针的位置的(可以&this获得),也可以直接使用的。
3.this指针不能在静态函数中使用,this指针不占类的内存。
4.友元函数没有 this 指针,因为友元不是类的成员。只有成员函数才有 this 指针。
5.用法:
在C++中,当成员函数中某个变量与成员变量名字相同,则使用this关键字来表示成员变量。
#include <iostream>
using namespace std;
class Student{
public:
void setname(char *name);
void setage(int age);
void setscore(float score);
void show();
private:
char *name;
int age;
float score;
};
void Student::setname(char *name){
this->name = name;
}
void Student::setage(int age){
this->age = age;
}
void Student::setscore(float score){
this->score = score;
}
void Student::show(){
cout<<this->name<<"的年龄是"<<this->age<<",成绩是"<<this->score<<endl;
}
int main(){
Student *pstu = new Student;
pstu -> setname("李华");
pstu -> setage(16);
pstu -> setscore(96.5);
pstu -> show();
return 0;
}
这就表示了,本对象的成员变量name,age,score被三个函数的参数给赋值。