一. this
指针的引出
我们先来定义一个日期类
Date
class Date
{
public :
void Display ()
{
cout <<_year<< "-" <<_month << "-"<< _day <<endl;
}
void SetDate(int year , int month , int day)
{
_year = year;
_month = month;
_day = day;
}
private :
int _year ; // 年
int _month ; // 月
int _day ; // 日
};
int main()
{
Date d1, d2;
d1.SetDate(2018,5,1);
d2.SetDate(2018,7,1);
d1.Display();
d2.Display();
return 0;
}
对于上述类,有这样的一个问题:
Date
类中有
SetDate
与
Display
两个成员函数,函数体中没有关于不同对象的区分,那当
s1
调用
SetDate
函数
时,该函数是如何知道应该设置
s1
对象,而不是设置
s2
对象呢?
C++
中通过引入
this
指针解决该问题,即:
C++
编译器给每个
“
非静态的成员函数
“
增加了一个隐藏的指针参
数,让该指针指向当前对象
(
函数运行时调用该函数的对象
)
,在函数体中所有成员变量的操作,都是通过该
指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成
。
二. this
指针的特性
1. this
指针的类型:类类型
* const
2.
只能在
“
成员函数
”
的内部使用
3.
this
指针本质上其实是一个成员函数的形参
,是对象调用成员函数时,将对象地址作为实参传递给
this
形参。所以
对象中不存储
this
指针
。
4.
this
指针是成员函数第一个隐含的指针形参,一般情况由编译器通过
ecx
寄存器自动传递,不需要用户
传递

再举一个栗子
#include <iostream>
using namespace std;
class Box
{
public:
// 构造函数定义
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
几个问题的探讨
1.this指针--》 类,对象 占不占用大小?
this指针不占用类的大小
编译器传递
2.this指针--》地址 地址里存放的是什么?
(this指针是指向自身的地址),指向对线的指针,对象的首地址
3.静态的 非静态的 静态的成员函数是没办法操作this?为什么?
(this指针是 编译器帮我们做的处理,不是我们自己写的)静态成员函数是先于对象存在的 是所有对象共有的 没有this
4.this指针可以为空嘛?
当以对象调用成员函数时,this指针不可能为空。
当以指针ptr调用成员函数时,是将ptr作为参数传递给this指针,若ptr为空,那么this指针为nullptr,this指针为空,成员函数可以正常调用。但若是成员函数访问了成员变量或者调用了有成员变量的成员函数,程序会崩溃。