在 C++ 中,this
指针是一个特殊的指针,它被隐式定义在所有非静态成员函数中。this
指针指向调用对象,即调用成员函数的对象的地址。通过使用 this
指针,成员函数能够访问调用它的对象的成员变量和其他成员函数。
this指针是一个指针常量 int * const p
核心特性和用法
-
访问成员变量和函数:
this
指针最常见的用途是在成员函数内部访问对象的其他成员(变量或函数)。这在成员变量的名字被局部变量遮蔽时尤其有用。class Widget { private: int data; public: void setData(int data) { this->data = data; // 使用 this-> 来明确地指定成员变量 } int getData() const { return this->data; // 明确地使用 this } };
-
返回对象本身的引用:
this
指针常用于实现链式调用,即一个成员函数调用完毕后返回对象本身,使得可以连续调用多个成员函数。class Widget { private: int x, y; public: Widget& setX(int x) { this->x = x; return *this; // 返回调用对象本身 } Widget& setY(int y) { this->y = y; return *this; } }; Widget w; w.setX(5).setY(10); // 链式调用
-
在构造器中区分参数和成员变量:
在构造函数中,如果参数名称与成员变量名称相同,可以使用this
指针来区分它们。class Point { private: double x, y; public: Point(double x, double y) { this->x = x; // 使用 this 指针区分成员变量和参数 this->y = y; } };
-
实现比较函数:
this
指针可用于比较两个对象是否相同。class Widget { public: bool isEqual(const Widget& other) { return this == &other; // 比较两个对象的地址 } };
特别注意
- 静态成员函数中不可用:由于静态成员函数不依赖于类的具体对象来调用,因此在静态成员函数中不能使用
this
指针。 this
是一个常量指针:this
实际上是一个指向对象的常量指针(Widget* const this
),意味着你不能更改this
指针本身指向的地址,但可以修改指针指向的对象的内容。
通过上述讨论,可以看出 this
指针是 C++ 类设计中一个非常有用的特性,它使得成员函数能够更灵活地访问和操作对象的成员。
通过以下例子,解释this,*this,&this->p_name,&p在内存中的分配
class Phone {
public:
string p_name;
Phone() {}
Phone(string name) : p_name(name) {
cout << "phone初始化" << endl;
}
~Phone() {
cout << "Phone析构" << endl;
}
Phone& test() {
cout << "test()" << endl;
cout << "&this->p_name=" << &this->p_name << endl;
cout << "this=" << this << endl;
return *this;
}
};
int main()
{
Phone p1("iphone");
cout << " *this=" << &p1.test() << endl;;
cout << "&p1" << &p1 << endl;
return 0;
}