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;
}
相关推荐
·present·11 小时前
CSAPP(lecture 4_01)
c语言·c++
FPGA小迷弟11 小时前
用 Claude Code 重构遗留系统:从评估到落地的完整实践指南
c++·python·ai·plotly·django·ai编程·claude
程序员-King.12 小时前
【ROS1】Noetic 开发工作流程与常用命令
c++·ubuntu·ros
云深麋鹿12 小时前
C++ | 基于红黑树实现mymap与myset
开发语言·c++
傲世仙尊13 小时前
string增删查改-insert-erase-replace与find加substr组合技
c++
·present·15 小时前
CSAPP(lecture 3)
c++
别动我齐刘海15 小时前
机器人 C++ / 系统联调补强2——异常处理、Protobuf
linux·c++·人工智能·学习·算法·机器学习·机器人
basketball61615 小时前
C++ 中字符串与常见类型的转换总结
开发语言·c++
等我调个Bug16 小时前
C++智能指针通俗讲解
开发语言·c++
kyle~18 小时前
时间同步 --- PTP 与 Scheduled Action Command
c++·数码相机·机器人·传感器