C++ this指针

 类中的成员函数(包括构造函数、析构函数)都有一个隐藏的当前类类型的指针参数,名为this。在成员函数中访问类中其它成员,其本质都是通过this来实现的

对于普通的成员函数,this指针就表示该成员函数调用对象

class Teacher {
public:
    Teacher(const string& name, int age) :m_name(name), m_age(age) {}
    void print(void) {
        cout << m_name << endl;
        cout << this->m_name << endl; //【this表示类创建的对象】
        cout << m_age << endl;
        cout << this << endl;  //打印this指针地址
    }
private:
    string m_name;
    int m_age;
};


int main()
{
    Teacher t1("李明", 52);
    t1.print();
    cout << &t1 << endl; //这个地址就是this地址
    return 0;
}

大多数情况下,this可以省略直接访问类中的成员

 

在以下四种场景中必须显示使用this指针:

一.区分作用域

class Teacher {
public:
    Teacher(string name, int age) {
        this->name = name; //用this来区分作用域
        this->age = age;
    }
    void print(void) {
        cout << name << endl;
        cout << age << endl;
       
    }
private:
    string name;
    int age;
};


int main()
{
    Teacher t("李明", 52);
    t.print();
    return 0;
}

 

 

二.返回值是对象自身的引用--重点掌握

 

class A {
public:
    A(int count) {
        this->count = count;
    }
    A& add(void) {
        count++;
        return *this;  //返回对象本身的引用
        //说明:this指向类对象;*this表示类对象本身
    }

    int count;
};

int main()
{
    A a(11);
    a.add().add().add();//a.add()的返回值是自身的引用,a.add()看作是a自身
    cout << a.count << endl;

    return 0;
}

 

 

三.从类的内部销毁对象自身--了解

 

class A {
public:
    A(int count) {
        this->count = count;
    }
    void xiaohui(void) {
        delete this;  //销毁对象自身
    }
    int count;
};

int main()
{
    A a(11);
    cout << a.count << endl;
    //a.xiaohui();  这是错的[delete必须跟new配对]

    A* p = new A(100);
    p->xiaohui(); // 这是对的
    
    return 0;
}

 

四.作为成员函数实参,实现对象之间交互---了解

#include <iostream>
#include<string>
using namespace std;

class Student; //类的短视声明
//因为Student类在Teacher类的下面,而Teacher类又要访问Student类,所以需要Student类的短视声明
class Teacher {
public:
    void educate(Student* s);
    void reply(const string& answer);

private:
    string m_answer;
    
};

class Student {
public:
    void ask(const string& q, Teacher* t);
};

void Teacher::educate(Student* s) {
    s->ask("你多大了?", this); //向学生提出问题
}

void Teacher::reply(const string& answer) {
    m_answer = answer;//记录学生的答案
    cout << "学生答案是:" << m_answer << endl;

}

void Student::ask(const string& q, Teacher* t) {
    cout << "问题是:" << q << endl;
    t->reply("我25岁");//向教师回答问题
}


int main()
{
    Teacher t;
    Student s;
    t.educate(&s);
    return 0;
}

 

 

 

 

 

 

 

posted @ 2019-02-25 05:45  天子骄龙  阅读(630)  评论(0编辑  收藏  举报