每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。
注意:友元函数没有 this 指针,因为友元不是类的成员。只有成员函数才有 this 指针。
示例代码 :
#include <iostream>
using namespace std;
class Array
{
public:
Array(int Len = 0) : Len(Len) { cout << "Array()" << endl; }
~Array() { cout << "~Array()" << endl; }
void setLen(int Len) { this->Len = Len; }
int getLen() { return Len; }
void print() {cout << "Len = " << Len << endl;}
private:
int Len;
};
void stackInstantiation()
{
Array arr1(5);
Array arr2;
arr2.setLen(7);
arr1.print();
arr2.print();
}
int main()
{
stackInstantiation();
return 0;
}
运行结果:
- 当参数名称与数据成员名称相同时可使用 this 指针区分。
- 当参数名称与数据成员名称相同时可使用初始化列表,如示例代码 中 Point 类。
- 以上两种方式可以区分参数和成员函数,但建议不要起相同的名称。
示例代码
#include <iostream>
using namespace std;
class Array
{
public:
Array(int Len = 0) : Len(Len) { cout << "Array()" << endl; }
~Array() { cout << "~Array()" << endl; }
// Array *setLen(int Len) {
// this->Len = Len;
// return this;
// }
Array &setLen(int Len) {
this->Len = Len;
return *this;
}
int getLen() { return Len; }
void print() {
cout << "Len = " << Len << endl;
}
private:
int Len;
};
void stackInstantiation()
{
Array arr1(5);
arr1.print();
arr1.setLen(7).print();
}
int main()
{
stackInstantiation();
return 0;
}
运行结果:
- 返回对象指针或者引用时的成员函数可以连续访问。
- 引用返回 *this 而指针返回 this。
示例代码
void stackInstantiation()
{
Array arr1(5);
cout << "this addr: " << arr1.setLen(7) << endl;
cout << "obj addr: " << &arr1 << endl;
Array arr2(3);
cout << "this addr: " << arr2.setLen(6) << endl;
cout << "obj addr: " << &arr2 << endl;
}
运行结果:
- this 指针就是对象本身的指针。
- 相同类型不同对象 this 指针指向不同的对象。
本文介绍了C++中的this指针,它是一个隐含的成员函数参数,用于在成员函数内部访问调用对象的地址。示例代码展示了如何在成员函数中使用this指针来设置和获取对象的长度,并通过this指针返回对象的引用或指针,实现连续操作。此外,还强调了this指针在区分参数和成员变量以及不同对象间的差异性上的作用。
300

被折叠的 条评论
为什么被折叠?



