this指针
概念:
this指针是一个常量指针,它存在于类的成员函数之中,它指向的被调用成员函数所实例化的对象。在成员函数内部,我们可以直接使用调用函数的对象的成员,而不用通过成员访问操作符来做到这一点,这就是因为this指针正指向该对象,任何对类成员的直接访问都被看做this的隐式访问。
代码示例
Complex &operator=(/*Complex *const this,*/ const Complex &a)//这里的参数列表中隐藏了一个this常量指针,该指针指向的正是调用该函数的对象
{
if (this == &a)
{
return *this;
}
_real = a._real;// this->_real = a._real;
_image = a._image;// this->_image = a._image;
return *this;
}
特性:
this指针的指针类型为 类类型 *const this,它是一个常量指针,所以不允许改变this的地址。
this指针并不是对象本身的一部分,不影响sizeodf的结果。
this指针的作用域只在类成员函数的内部。
this指针只适用于非静态的成员函数。
this指针是类成员函数的第一个默认参数,编译器自动维护传递,类的编写者不能显式的传递。
示例
Complex &operator=(Complex *const this,const Complex &a)//显式传递this指针
{
if (this == &a)
{
return *this;
}
this->_real = a._real;
this->_image = a._image;
return *this;
}
上述情况编译器会报错。