C++之this指针

文章目录

什么是this指针

  • 不同的对象各自拥有独立的成员变量,但它们共享同一份成员函数代码,那么在成员函数中如何区分所访问的成员变量隶属于哪个对象?
    • 是this指针
cpp 复制代码
#include <iostream>
using namespace std;
class Student{
public:
    Student(int age, const string &name){
        m_age = age;
        m_name = name;
    }
    void print(){
        cout << m_name << ":" << m_age << endl;
    }
private:
    int m_age;
    string m_name;
};
int main(void){
    Student zs(12, "zhangsan");
    Student ls = Student(13, "lisi");
    zs.print();
    ls.print();
    return 0;
}
  • this是一个用于标识对象自身的隐式指针,代表对象自身的地址
  • 在编译类成员函数时,C++编译器会自动将this指针添加到成员函数的参数表中。在用类的成员函数时,调用对象会把自己的地址通过this指针传递给成员函数
  • 以上程序编译器编译后的样子,大致如下:
cpp 复制代码
#include <iostream>
using namespace std;
class Student{
public:
    Student(Student *this, int age, const string &name){
        this->m_age = age;
        this->m_name = name;
    }
    void print(Student *this){
        cout << this->m_name << ":" << this->m_age << endl;
    }
private:
    int m_age;
    string m_name;
};
int main(void){
    Student zs(12, "zhangsan"); // (&zs, 12, "zhangsan")
    Student ls = Student(13, "lisi");
    zs.print(); //print(&zs)
    ls.print();//print(&ls)
    return 0;
}

this指针的应用

  • 需要显示使用this指针的常见场景:
    • 类中的成员变量和参数变量名字一样,可以通过this指针区分
    • 从成员函数中返回调用对象自身(返回自引用),支持链式调用
    • 在成员函数中销毁对象自身(对象自销毁)
cpp 复制代码
#include <iostream>
using namespace std;
class Counter{
private:
    int count;
public:
    Counter(int count = 0){
        this->count = count;
    }
    Counter &add(void){
        ++count;
    return *this;
    }
    void print(void){
        cout << count << endl;
    }
    void destroy(void){
        cout <<"this : " << this << endl;
        delete this; //销毁对象本身
    }
};
int main(void){
    Counter cnt;
    cnt.print();
    cnt.add().add().add();
    cnt.print();
    Counter *pcn = new Counter;
    pcn->add();
    pcn->print();
    pcn->destroy();
    cout<<"pcn: " <<pcn <<endl;
    return 0;
}
相关推荐
云姜.17 小时前
java多态
java·开发语言·c++
CoderCodingNo17 小时前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
陳103017 小时前
C++:红黑树
开发语言·c++
一切尽在,你来17 小时前
C++ 零基础教程 - 第 6 讲 常用运算符教程
开发语言·c++
weixin_4997715517 小时前
C++中的组合模式
开发语言·c++·算法
近津薪荼18 小时前
dfs专题5——(二叉搜索树中第 K 小的元素)
c++·学习·算法·深度优先
xiaoye-duck18 小时前
吃透 C++ STL list:从基础使用到特性对比,解锁链表容器高效用法
c++·算法·stl
_F_y18 小时前
C++重点知识总结
java·jvm·c++
初願致夕霞19 小时前
Linux_进程
linux·c++