C++——this指针

this就是一个指针,指向当前对象,当前调用成员函数的这个对象,它在每个非静态成员对象中都隐式存在。

成员函数的调用者是谁,this就指向谁

一、在非静态成员函数中

ClassName* const this

以这样的形式存在,const在类型后面表示它的指向不能被修改,只能指向该对象,不过可以修改当前对象的内容

二、调用形式

1、修改对象内容

这份代码,如果没有使用this->age进行修改的话,同名的形参无法给内置类型成员age进行修改,但用下面的方式就可以进行修改。

cpp 复制代码
class Person {
private:
    int age;
public:
    void setAge(int age) {
        this->age = age; // 使用 this 区分成员变量和形参
    }
};

2、链式调用

this指向当前对象

*this是当前对象的引用

返回 *this 可让调用者继续使用当前对象执行下一个操作。

cpp 复制代码
class Point {
private:
    int x, y;
public:
    Point& setX(int x) { this->x = x; return *this; }
    Point& setY(int y) { this->y = y; return *this; }
};

int main() {
    Point p;
    p.setX(10).setY(20); // 链式调用
}

3、在类内当做其他成员函数的参数

在类的内部,把当前对象传递给其他的成员函数

cpp 复制代码
class Dog {
public:
    void bark() { std::cout << "Woof!\n"; }
    void playWith(Dog& other) {
        std::cout << "Playing with another dog\n";
    }
    void invitePlay() {
        playWith(*this); // 将当前对象传给另一个函数
    }
};

三、this在const成员函数中的使用

类型名前面的const表示其内容无法进行修改

cpp 复制代码
const ClassName* const this;
cpp 复制代码
class Box {
private:
    int width;
public:
    void show() const {
        // this->width = 10; // ❌ 错误,不能修改
        std::cout << this->width << std::endl;
    }
};

四、静态成员函数没有this指针

cpp 复制代码
class Counter {
private:
    static int count;  // 静态成员变量(所有对象共享)
    int id;            // 普通成员变量
public:
    Counter() { count++; id = count; }

    static void showCount() {
        cout << "count = " << count << endl; // ✅ 可访问静态变量
        // cout << id; // ❌ 错误:静态函数中没有 this
    }
};
int Counter::count = 0; // 静态变量定义
相关推荐
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
端平入洛5 天前
auto有时不auto
c++
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20216 天前
信号量和信号
linux·c++