this指针

class A
{
public:
     A(int x1)
     {
          x=x1;
     }
     void disp()
     {
          cout<<"this="<<this<<" when x="<<this->x<<endl;
     }
private:
     int x;
};
int main()
{
     A a(1),b(2),c(3);
     a.disp();
     b.disp();
     c.disp();
     return 0;
}
this指针有可能指向NULL
class CTest
{
public:
     void FunTest()
     {
          cout<<"this:"<<this<<endl;
     }
};
 
void FunTest()
{
     CTest* pt=NULL;//定义一个类对象的指针并使其初始化为NULL
     pt->FunTest();
}
int main()
{
     FunTest();
     return 0;
}
(1).this指针在成员函数的开始执行前构造的,在成员结束后清楚
(2).this指针因编译器不同,存放的位置不同,可能是stack、也可能是register、也可能是全局变量
(3).this指针只有在成员函数中才有定义。你获得一个对象后也不能通过对象使用this指针
     我们无法知道一个对象的this指针的位置
     在成员函数里,我们可以(&this)获得this指针的位置,也可以直接使用
(4).一般编译器通过ecx寄存器来传递this指针,否则不同编译器产生的obj就无法匹配
    this是通过函数参数的首参来传递的
(5).静态成员函数和变量都是独立于类的实例对象之外的,所以他不能用this指针也不能操作非静态成员
安心下来做技术,笑是最大的福气
原文地址:https://www.cnblogs.com/JN-PDD/p/6613964.html