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;
}
相关推荐
clint4562 天前
C++进阶(1)——前景提要
c++
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾3 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 天前
constexpr函数
c++
凡人叶枫3 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫3 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss3 天前
BRpc使用
c++·rpc
-森屿安年-3 天前
63. 不同路径 II
c++·算法·动态规划