在学习 C++面向对象编程 的过程中,this 指针是一个非常重要的概念。很多初学者对它感到困惑,不知道它到底是什么、有什么用。本文将用通俗易懂的语言,配合实例代码,带你彻底搞懂 C++ this指针 的本质和使用方法。

在 C++ 中,每个非静态成员函数都会隐式地接收一个额外的参数——一个指向调用该函数的对象的指针,这个指针就是 this 指针。
简单来说:this 是一个指向当前对象本身的指针。它只在类的非静态成员函数内部有效。
假设我们有一个类 Person:
class Person {public: std::string name; int age; void introduce() { std::cout << "我叫 " << name << ",今年 " << age << " 岁。" << std::endl; }};当你创建一个对象并调用其成员函数时:
Person p;p.name = "张三";p.age = 25;p.introduce();实际上,编译器会把 p.introduce() 转换为类似这样的调用:
introduce(&p); // 隐式传入对象地址而 introduce 函数内部其实有一个隐藏的参数:
void introduce(Person* this) { std::cout << "我叫 " << this->name << ",今年 " << this->age << " 岁。" << std::endl;}所以,你在成员函数中写的 name,其实是 this->name 的简写形式!
当函数参数或局部变量与成员变量同名时,可以用 this-> 明确指定访问的是成员变量:
class Student {private: std::string name;public: void setName(std::string name) { this->name = name; // 左边是成员变量,右边是参数 } std::string getName() const { return this->name; }};通过返回 *this(即当前对象的引用),可以实现链式调用:
class Counter {private: int value = 0;public: Counter& add(int n) { this->value += n; return *this; // 返回当前对象的引用 } void print() const { std::cout << "当前值: " << value << std::endl; }};// 使用示例Counter c;c.add(5).add(3).print(); // 输出:当前值: 8例如在赋值运算符 = 重载中,常需要返回 *this 以支持连续赋值:
MyClass& operator=(const MyClass& other) { if (this != &other) { // 自赋值检查 // 复制成员... } return *this;}this 赋值,比如 this = nullptr; 是非法的。ClassName* const;对于 const 成员函数,它是 const ClassName* const。通过本文,你应该已经理解了 C++ this指针 的基本概念和主要用途。它是 C++ 面向对象机制的核心之一,帮助我们在成员函数中明确操作的是哪个对象的数据。
记住几个关键点:
this 是指向当前对象的指针掌握 this指针用法,是迈向熟练使用 C++类成员函数 和高级面向对象编程的重要一步。多写代码、多调试,你会越来越得心应手!
本文由主机测评网于2025-12-05发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025123237.html