this指针(C++)

this指针作为一个隐含参数传递给非静态成员函数,用以指向该成员函数所属类所定义的对象。当不同的对象调用同一个类的成员函数代码时,编译器会依据该成员函数的this指针所指向的不同对象来确定应该引用哪个对象的数据成员。

在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。

  1. #include<iostream>  
  2. #include<string>  
  3. using namespace std;  
  4. class Stu_Info_Mange  
  5. {  
  6.     int sno;  
  7.     string sname;  
  8.     int age;  
  9.     int grade;  
  10. public:  
  11.     Stu_Info_Mange(int s=0,string n="",int a=0,int g=0)  
  12.     {  
  13.         sno=s;  
  14.         sname=n;  
  15.         age=a;  
  16.         grade=g;  
  17.     }  
  18.     void Setsname(int sn)   //使用this指针进行赋值  
  19.     {  
  20.         this->sname=sn;  
  21.     }  
  22.     int  Setage(int a)  
  23.     {  
  24.         this->age=a;  
  25.         return (*this).age; //使用this指针返回该对象的年龄  
  26.     }  
  27.     void print()  
  28.     {  
  29.         cout<<"the sname is "<<this->sname<<endl;  //显式this指针通过箭头操作符访问  
  30.         cout<<"the sno   is "<<sno<<endl;//隐式使用this指针打印  
  31.         cout<<"the age   is "<<(*this).age<<endl;//显式使用this指针通过远点操作符  
  32.         cout<<"the grade is "<<this->grade<<endl<<endl;  
  33.     }  
  34.   
  35. };  
  36. int main()  
  37. {  
  38.     Stu_Info_Mange sim1(761,"张三",19,3);  
  39.   
  40.     sim1.print();      //输出信息  
  41.   
  42.     sim1.Setage(12);  //使用this指针修改年龄  
  43.   
  44.   
  45.     sim1.print();     //再次输出  
  46.     return 0;  
  47. }  


#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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值