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; // 静态变量定义
相关推荐
千里马-horse16 小时前
CallbackInfo
c++·node.js·napi·callbackinfo
serendipity_hky16 小时前
【go语言 | 第6篇】Go Modules 依赖解决
开发语言·后端·golang
何小义的AI进阶路16 小时前
win下 vscode下 C++和opencv的配置与使用
c++·图像处理·vscode·opencv
小oo呆16 小时前
【学习心得】Python的TypedDict(简介)
开发语言·python
文洪涛16 小时前
VS Code Python “第一次运行失败 / 先执行 python 再激活 Conda” 问题定位与解决
开发语言·python·conda
wanghowie16 小时前
01.08 Java基础篇|设计模式深度解析
java·开发语言·设计模式
wjs202416 小时前
Memcached stats 命令详解
开发语言
云技纵横17 小时前
Stream API 从入门到实践:常用操作、易错点与性能建议
开发语言·windows·python
Knight_AL17 小时前
Java 17 新特性深度解析:记录类、密封类、模式匹配与增强的 switch 表达式对比 Java 8
java·开发语言
吴佳浩 Alben17 小时前
Go 1.25.5 通关讲解
开发语言·后端·golang