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; // 静态变量定义
相关推荐
郝学胜_神的一滴9 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天1 天前
C++ 基础入门完全指南
c++
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK3 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境3 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境3 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴4 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境6 天前
C++ 的Eigen 库全解析
c++
卷无止境6 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴6 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake