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; // 静态变量定义
相关推荐
小冯的编程学习之路2 小时前
【C++】: C++基于微服务的即时通讯系统(1)
开发语言·c++·微服务
穿西装的水獭3 小时前
python将Excel数据写进图片中
开发语言·python·excel
老友@3 小时前
Java Excel 导出:EasyExcel 使用详解
java·开发语言·excel·easyexcel·excel导出
淀粉肠kk3 小时前
【C++】map和set的使用
c++
tryCbest3 小时前
Python基础之爬虫技术(一)
开发语言·爬虫·python
hixiong1233 小时前
C# OpenCVSharp实现Hand Pose Estimation Mediapipe
开发语言·opencv·ai·c#·手势识别
集成显卡3 小时前
AI取名大师 | PM2 部署 Bun.js 应用及配置 Let‘s Encrypt 免费 HTTPS 证书
开发语言·javascript·人工智能
AI小云3 小时前
【Numpy数据运算】数组间运算
开发语言·python·numpy
是苏浙4 小时前
零基础入门C语言之C语言实现数据结构之单链表经典算法
c语言·开发语言·数据结构·算法