C++关键字—this
一、this是什么
- this 是 C++ 中的一个关键字
- this是一个 const 指针
- this 指针是所有成员函数的隐含参数
二、this可以用在哪
- this 只能用在类的内部
- this可用于调用类的成员函数和成员变量
三、this可以用来做什么
- 它指向当前对象,通过它可以访问当前对象的所有成员(包括 private、protected、public 属性的成员)
- 友元函数没有 this 指针,因为友元不是类的成员。只有成员函数才有 this 指针。
注意,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;
}