Date
May. 19th, 2024
 
2024年 4月 12日

Post: C++ Primer 013 : this 指针

C++ Primer 013 : this 指针

Published 12:05 May 25, 2013.

Created by @ezra. Categorized in #Programming, and tagged as #C/C++.

Source format: Markdown

Table of Content

本篇主要介绍 C++ 中的 this 指针。

关键字 this 就是一个指针,对于成员函数而言 this 指针指向调用对象的地址,而对于构造函数而言this指针指向正在被创建的对象的地址。

  • 可以用于区分构造函数中成员变量名和行参名相同的情况(使用初始化列表例外)
this->m_name = m_name;
  • 可以用于返回自引用的情况

  • 可以作为函数的参数来实现对象间的交互

/*
    this 指针用于区分构造函数中成员变量名和行参名相同的情况(使用初始化列表例外)this1.cpp
*/
#include <iostream>
#include <string>

using namespace std;

class Student {
private:
    string m_name;//姓名
    int m_age;//年龄
public:
    //定义一个有参构造函数
    Student(const string &name,int age):m_name(name),m_age(age) {
        cout << "构造函数中:this = " << this << endl;
    }
    void show(void) {
        cout << "构造函数中:this = " << this << endl;
        cout << "我是" << m_name << ",今年" << m_age << "岁" << endl;
    }
};

int main(void) {
    Student s("张飞",30);
    s.show();
    cout << "main函数中:&s = " << &s << endl;
    Student s2("关于",30);
    s2.show();
    cout << "main函数中:&s2 = " << &s2 << endl;
    return 0;
}
/*
    this 指针用于返回自引用的情况this2.cpp
*/
#include <iostream>

using namespace std;

class Counter {
private:
    int m_count;
public:
    //初始化计数值
    Counter(int count = 0):m_count(count){}
    //记数加1的成员函数
    Counter& increase(void) {
        m_count++;
        //返回自引用
        return *this;
    }
    //记数减1的成员函数
    Counter& decrease(void) {
        m_count--;
        return *this;
    }
    //打印计数当前值
    void show(void) {
        cout << "当前计数值为" << m_count << endl;
    }
};

int main(void) {
    Counter c;
    c.increase().increase().increase().decrease().show();
    return 0;
}
/*
    this 指针作为函数的参数来实现对象间的交互this3.cpp
*/
#include <iostream>
#include <string>

using namespace std;

class Student;
class Teacher {
private:
    string m_answer;//保存老师的回答
public:
    //给学生上课的函数
    void educate(Student *ps);
    /*{
        ps->ask("什么叫this指针?");
        cout << m_answer << endl;
    }*/
    //回答学生问题的函数
    void replay(const string &str) {
        m_answer = str;
    }
};

class Student {
public:
    //想老师提问的函数
    void ask(const string &question,Teacher *pt) {
        cout << question << endl;
        pt->replay("this指针就是调用对象的地址!!");
    }
};

Teacher::void educate(Student *ps) {
    ps->ask("什么叫this指针?");
    cout << m_answer << endl;
}

int main(void) {
    Teacher t;
    Student s;
    t.educate(&s);
    return 0;
}
Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF