【c++】this指针学习与理解
this指针是 C++ 中一个核心但常被忽略的概念。
“Inside every member function, the keyword
thisis a const pointer that holds the address of the current implicit object.”
🧩 一、member function(成员函数)与对象的关系
当你写一个类:
class Person {
public:int age;void sayHello() {std::cout << "Hello, my age is " << age << std::endl;}
};
然后在 main() 里这样写:
Person p1;
p1.age = 20;
p1.sayHello();
看起来你在调用一个函数,但实际上编译器会偷偷地把它改写成:
Person::sayHello(&p1);
也就是说,成员函数的本质其实是一个带有额外隐藏参数的普通函数,这个隐藏参数就是 this 指针。
🧠 二、this 是什么?
在每个非静态成员函数中,编译器都会自动为你加上一个参数:
void Person::sayHello(Person* const this)
也就是说,this 是一个指向当前对象的常量指针(pointer to the current object)。
- 它的类型是:
Person *const this
(意味着this自身不能被改指向别的对象) - 但
*this(它所指向的对象)可以修改。
所以可以写this->age = 30;
🧾 三、“const pointer”是什么意思?
“const pointer” 不是“指向常量的指针”,而是“指针本身是常量”。
对比:
| 类型 | 含义 |
|---|---|
const int* p | 指向常量的指针(不能改值,但能改指向) |
int* const p | 常量指针(能改值,但不能改指向) |
this 属于第二种:ClassName* const this。
你不能让 this 指向别的对象:
this = &anotherObject; // ❌ 错误:this 是 const pointer
但你可以通过它修改当前对象的内容:
this->age = 30; // ✅ OK
🧮 四、一个形象的例子
class Box {
public:int width;void setWidth(int w) {this->width = w; // “this” 指向调用该函数的对象}
};
使用:
Box b1, b2;
b1.setWidth(10); // => 编译器其实做了:setWidth(&b1, 10)
b2.setWidth(20); // => setWidth(&b2, 20)
所以在第一次调用中:
-
this == &b1 -
第二次调用中:
this == &b2
🧱 五、const 成员函数中的 this
如果函数被声明为 const,比如:
void print() const {std::cout << this->width << std::endl;
}
那此时 this 的类型变为:
const Box *const this
也就是说:
this依然是个常量指针(不能改指向)- 但它指向一个常量对象(不能改成员)
因此,在 const 成员函数里,你不能写 this->width = 5;。
✅ 总结
| 概念 | 含义 |
|---|---|
this 是什么 | 指向当前对象的隐藏指针 |
| 类型 | ClassName* const this |
| 存在范围 | 所有非静态成员函数中 |
| 用途 | 访问当前对象的成员(this->member) |
| const 成员函数中 | 类型变为 const ClassName* const this |
