• C++:this指针



    this指针
    this关键字:表示本类中的对象成员,可以通过this指针访问当前类的成员
    //举例

    //例 3.18  隐藏this指针的引例 
    #include<iostream>
    using namespace std;
    class A{
     public:
           A(int x1)
           {
             x = x1;
           }
           void dis()
           {
            cout<<"x = "<<x<<endl;
           } 
           private:
            int x;
    };
    int main()
    {
     A a(1),b(2);
     cout<<"a:";
     a.dis();
     cout<<"b:";
     b.dis();
     return 0;
    } 
    
    /*
      运行结果:  a:x = 1
                b:x = 1
    @当this指针指向a时:            
    cout<<"x = "<<x<<endl ----> cout<<"x = "<<this->x<<endl ---> cout<<"x = "<<a.x<<endl
    @成员函数:void dis()
               {
                 cout<<"x = "<<x<<endl;
               } 
     实际使用时,C++编译系统把它处理为:
              void dis(*this)
              {
                 cout<<"x = "<<this->x<<endl
              } 
           此时:调用a.dis()---->调用a.dis(&a),这样在进行函数调用时,编译系统就对象
                   a的地址传给形参this指针,成员函数执行后,输出了a.x的值。
    */
    
    //例3.19  显示this指针的值
    #include<iostream>
    using namespace std;
    class A{
      public:
            A(int x1)
            {
                x = x1;
            }
            void dis()
            {
             cout<<"this = "<<this<<" when x="<<this->x<<endl;
            }
      private:
            int x;        
    };
    int main()
    {
     A a(1),b(2),c(3);
     a.dis();
     b.dis();
     c.dis();
     return 0;
    }    
           
        运行结果:   this = 0012FF7C  when x = 1
                   this = 0012FF78  when x = 2
                   this = 0012FF74  when x = 3           
  • 相关阅读:
    C#中调用Outlook API 发起会议
    Log4Net配置
    web端调用Webapi获取Excel表格
    表格导出之Aspose.Cells
    验证输入框
    把新建的对象所有属性变成默认值
    省市区三级联动
    全局异常处理
    HttpHttpServletRequest / Reponse
    热部署
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/4911869.html
Copyright © 2020-2023  润新知