cpp this指针
- 在 C++ 中,this 指针是一个特殊的指针,它指向当前对象的实例。
- 在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。
- this是一个隐藏的指针,可以在类的成员函数中使用,它可以用来指向调用对象。
- 当一个对象的成员函数被调用时,编译器会隐式地传递该对象的地址作为 this 指针。在成员函数中的形参样式为:class_name* const this
- 友元函数没有 this 指针,因为友元不是类的成员,只有成员函数才有 this 指针。
- 静态成员函数(
static
)属于类,不关联任何对象实例,因此没有this
指针
核心作用
1.避免命名冲突
class Rectangle {
private:double width; // 成员变量double height; // 成员变量
public:Rectangle(double width, double height) {this->width = width; // this->width 是成员变量,width 是参数this->height = height; // this->height 是成员变量,height 是参数}
};
2.返回当前对象的引用(链式调用)
class StringBuilder {
private:std::string str;
public:StringBuilder& append(const std::string& s) {str += s;return *this; // 返回当前对象的引用}StringBuilder& reverse() {std::reverse(str.begin(), str.end());return *this;}std::string get() const { return str; }
};int main() {StringBuilder sb;sb.append("Hello").append(" ").append("C++").reverse(); // 链式调用std::cout << sb.get() << std::endl; // 输出:++C olleHreturn 0;
}
this
指针是 C++ 中实现 “对象成员函数操作自身状态” 的核心机制,其本质是指向当前对象的隐式指针。它解决了成员变量与参数的命名冲突、支持链式调用、确保 const
成员函数的逻辑不变性,并区分不同对象实例的状态。
在 C++ 中,成员函数内部访问成员变量时,this->
是隐式存在的,因此在没有命名冲突的情况下,省略 this->
完全不影响代码的运行效果。
参考:
this指针,