查看: 129|回复: 0

C++ this指针详解

[复制链接]

8

主题

11

帖子

15

积分

新手上路

Rank: 1

积分
15
发表于 2023-10-14 19:52:30 | 显示全部楼层 |阅读模式
  • #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;
  • }


运行结果:
李华的年龄是16,成绩是96.5

this 只能用在类的内部,通过 this 可以访问类的所有成员,包括 private、protected、public 属性的。

本例中成员函数的参数和成员变量重名,只能通过 this 区分。以成员函数setname(char *name)为例,它的形参是name,和成员变量name重名,如果写作name = name;这样的语句,就是给形参name赋值,而不是给成员变量name赋值。而写作this -> name = name;后,=左边的name就是成员变量,右边的name就是形参,一目了然。

注意,this 是一个指针,要用->来访问成员变量或成员函数。

this 虽然用在类的内部,但是只有在对象被创建以后才会给 this 赋值,并且这个赋值的过程是编译器自动完成的,不需要用户干预,用户也不能显式地给 this 赋值。本例中,this 的值和 pstu 的值是相同的。

我们不妨来证明一下,给 Student 类添加一个成员函数printThis(),专门用来输出 this 的值,如下所示:
  • void Student::printThis(){
  •     cout<<this<<endl;
  • }


然后在 main() 函数中创建对象并调用 printThis():
  • Student *pstu1 = new Student;
  • pstu1 -> printThis();
  • cout<<pstu1<<endl;
  • Student *pstu2 = new Student;
  • pstu2 -> printThis();
  • cout<<pstu2<<endl;


运行结果:
0x7b17d8
0x7b17d8
0x7b17f0
0x7b17f0

可以发现,this 确实指向了当前对象,而且对于不同的对象,this 的值也不一样。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表