文章目录
this指针
this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。所谓当前对象,是指正在使用的对象。例如对于stu.show();,stu 就是当前对象,this 就指向 stu。
注意,this 是一个指针,要用->来访问成员变量或成员函数。
#include <iostream>
using namespace std;
class Student{
public:
void setname(string name);
void setage(int age);
void setscore(float score);
void show();
private:
string name;
int age;
float score;
};
void Student::setname(string 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();
delete pstu;
return 0;
}
输出结果:
this 虽然用在类的内部,但是只有在对象被创建以后才会给 this 赋值,并且这个赋值的过程是编译器自动完成的,不需要用户干预,用户也不能显式地给 this 赋值。本例中,this 的值和 pstu 的值是相同的。
#include <iostream>
using namespace std;
class Student{
public:
void printThis();
private:
string name;
int age;
float score;
};
void Student::printThis()
{
cout<<"this:"<<" "<<this<<endl;
}
int main(){
Student *stu1 = new Student;
stu1->printThis();
cout<<"stu1:"<<" "<<stu1<<endl;
Student *stu2 = new Student;
stu2->printThis();
cout<<"stu2:"<<" "<<stu2<<endl;
delete stu1,stu2;//释放
return 0;
}
输出结果: