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; // 静态变量定义