1、this指针的引出
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout <<_year<< "-" <<_month << "-"<< _day <<endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
int main()
{
Date d1, d2;
d1.Init(2022,1,11);
d2.Init(2022, 1, 12);
d1.Print();
d2.Print();
return 0;
}
2、this指针的特性
1. “this” 指针的含义
“this” 指针是在成员函数内部自动可用的。它指向当前对象本身。与普通指针不同,“this” 指针是一个常量指针,指向的对象是不可变的。这意味着我们无法修改 “this” 指针的值。
2. “this” 指针的用途
“this” 指针在以下几个方面具有重要作用:
2.1 访问成员变量
在成员函数中,可以使用 “this” 指针来访问当前对象的成员变量。例如,this->x
表示访问当前对象的成员变量 x
。当成员变量与函数参数名字相同时,使用 “this->” 可以明确指定要访问的是成员变量而非函数参数。
class MyClass {
private:
int x;
public:
void setX(int x) {
this->x = x;
}
int getX() {
return this->x;
}
};
在上述示例中,this->x
用于访问当前对象的成员变量 x
。
2.2 解决命名冲突
当派生类中的成员变量或成员函数与基类中的同名时,可能会出现命名冲突。此时,可以使用 “this” 指针来解决冲突。通过在 “this” 指针前面加上作用域限定符,我们可以明确指定要访问的是基类中的成员。
class Base {
public:
int x;
};
class Derived : public Base {
public:
void setX(int x) {
this->Base::x = x;
}
int getX() {
return this->Base::x;
}
};
在上述示例中,this->Base::x
被用于访问基类 Base
中的成员变量 x
。
2.3 返回当前对象
有时候我们需要在成员函数中返回当前对象本身,以便支持链式调用。这在构建流畅的接口时非常有用。我们可以使用 return *this;
语句返回当前对象。
class MyClass {
private:
int x;
public:
MyClass(int x) : x(x) {}
MyClass& add(int y) {
x += y;
return *this;
}
int getValue() {
return x;
}
};
int main() {
MyClass obj(10);
obj.add(5).add(7);
cout << obj.getValue() << endl; // 输出 22
return 0;
}
在上述示例中,add
函数返回当前对象 *this
,从而支持链式调用,可以连续调用多个 add
函数。
2.4 作为函数参数传递
有时候我们需要将当前对象作为参数传递给其他函数。通过使用 “this” 指针,我们可以将当前对象传递给其他函数以供使用。
class MyClass {
private:
int x;
public:
void print() {
cout << "Value: " << this->x << endl;
}
void callAnotherFunction() {
anotherFunction(this);
}
void anotherFunction(MyClass* obj) {
obj->print();
}
};
在上述示例中,print
函数使用了 “this” 指针来打印输出当前对象的成员变量 x
。然后,在 callAnotherFunction
函数中,我们将当前对象的地址作为参数传递给了 anotherFunction
函数,通过使用指针来访问当前对象的成员函数。