• C++ this指针


    this是C++中的一个关键字,也是一个const指针,它指向当前对象,通过它可以访问当前对象的所有成员。

    所谓当前对象,就是正在使用的对象。例如对于stu.show(),stu就是当前对象,this就指向stu。

    #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赋值。

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

    //给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;
    
    //运行结果:
    0x7c1510
    0x7c1510
    0x7c1530
    0x7c1530
    

    this确实指向了当前对象,而且对于不同的对象,this的值也不一样。

    注意:

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

    this到底是什么?

    this实际上是成员函数的一个形参,在调用成员函数时将对象的地址作为实参传递给this。不过this这个形参是隐式的,它并不出现在代码中,而是在编译阶段由编译器默默的将它添加到参数列表中。

    this作为隐式形参,本质上是成员函数的局部变量,所以只能用在成员函数的内部,并且只有在通过对象调用成员函数时才给this赋值。

    成员函数最终被编译成与对象无关的普通函数,除了成员变量,会丢失所有信息,所以编译时要在成员函数中添加一个额外的参数,把当前对象的首地址传入,依次来关联成员函数和成员变量。这个额外的参数,实际上就是this,它是成员函数和成员变量关联的桥梁。

  • 相关阅读:
    Android 判断现在系统存储器是“手机存储”还是“SD存储”
    Android中Is library配置的作用
    [已解决]报错: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Users/mac/Ana
    [未解决]报错:ssh_exchange_identification: read: Connection reset by peer
    Python快速设置Excel表格边框
    Python字典排序
    Scrapy框架: Request回调函数
    Scrapy框架: 异常错误处理
    Scrapy框架: 通用爬虫之SitemapSpider
    Scrapy框架: 通用爬虫之CSVFeedSpider
  • 原文地址:https://www.cnblogs.com/xiaobaizzz/p/12172041.html
Copyright © 2020-2023  润新知