C++中this指针的理解

1、this指针的用法

this是C++语言中的一个关键字,也是一个const指针,它指向当前对象,通过this指针可以访问当前对象的所有成员,所谓当前对象,是指正在使用的对象,例如:对于stu.show();,stu就是当前对象,而this指针就是指向stu。

下面是this指针用法的一个简单示例:

#include <iostream>

using namespace std;

class Student {
public:
    void set_name(char *name);
    void set_age(int age);
    void show_info(void);
private:
    char *name;
    int age;
};

void Student::set_name(char *name)
{
    this->name = name;
}

void Student::set_age(int age)
{
    this->age = age;
}

void Student::show_info(void)
{
    cout << "name: " << this->name << endl;
    cout << "age: " << this->age << endl;
}

int main(void)
{
    Student *pstu = new Student;
    pstu->set_name((char *)"Allen");
    pstu->set_age(18);
    pstu->show_info();
    
    return 0;
}

编译完成后运行结果为如下:

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

在上述示例中,成员函数的参数和成员变量重名,只能通过this指针进行区分。

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

this指针虽然在类的内部,但是只有在对象被创建以后才会给this指针赋值,并且这个赋值的过程是编译器自动完成的,不需要用户去干预,用户也不能显式地给this赋值,在上面代码中,this的值和pstu的值是相同的,可以使用下面代码证明:

#include <iostream>

using namespace std;

class Student {
public:
    void set_name(char *name);
    void set_age(int age);
    void show_info(void);
    void print_this(void);
private:
    char *name;
    int age;
};

void Student::set_name(char *name)
{
    this->name = name;
}

void Student::set_age(int age)
{
    this->age = age;
}

void Student::show_info(void)
{
    cout << "name: " << this->name << endl;
    cout << "age: " << this->age << endl;
}

void Student::print_this(void)
{
    cout << "this addr: " << this << endl;
}

int main(void)
{
    Student *pstu = new Student;
    pstu->set_name((char *)"Allen");
    pstu->set_age(18);
    pstu->show_info();
    
    //print addr
    cout << "pstu addr: " << pstu << endl;
    pstu->print_this();
    
    return 0;
}

代码修改后,编译并执行,输出结果如下:

从结果中可以看到pstu的值和this的值是一致的,this指针确实指向了当前对象。

在使用this指针时,需要注意下面几点:

  • this指针是const指针,它的值是不能被修改的,一切企图修改该指针的操作,如赋值、递增和递减等都是不允许的;
  • this指针只能在成员函数内部使用,用在其它地方没有意义,也是非法的;
  • 只有当对象被创建后,this指针才有意义,因此不能在static成员函数中使用。

 

2、this指针的本质

this指针实际上是成员函数的一个形参,在调用成员函数时将对象的地址作为实参传递给this指针,不过this这个形参是隐式的,它并不出现在代码中,而是在编译阶段由编译器默默地将它添加到参数列表中,this本质上是成员函数的局部变量,所以只能用在成员函数的内部,并且只有在通过对象调用成员函数时才给this赋值。

posted @ 2022-03-20 10:26  liangliangge  阅读(272)  评论(0编辑  收藏  举报