C++中的this指针

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

    #include<iostream>  
    #include<string>  
    using namespace std;  
    class Stu_Info_Mange  
    {  
        int sno;  
        string sname;  
        int age;  
        int grade;  
    public:  
        Stu_Info_Mange(int s=0,string n="",int a=0,int g=0)  
        {  
            sno=s;  
            sname=n;  
            age=a;  
            grade=g;  
        }  
        void Setsname(int sn)   //使用this指针进行赋值  
        {  
            this->sname=sn;  
        }  
        int  Setage(int a)  
        {  
            this->age=a;  
            return (*this).age; //使用this指针返回该对象的年龄  
        }  
        void print()  
        {  
            cout<<"the sname is "<<this->sname<<endl;  //显式this指针通过箭头操作符访问  
            cout<<"the sno   is "<<sno<<endl;//隐式使用this指针打印  
            cout<<"the age   is "<<(*this).age<<endl;//显式使用this指针通过远点操作符  
            cout<<"the grade is "<<this->grade<<endl<<endl;  
        }  
      
    };  
    int main()  
    {  
        Stu_Info_Mange sim1(761,"张三",19,3);  
      
        sim1.print();      //输出信息  
      
        sim1.Setage(12);  //使用this指针修改年龄  
      
      
        sim1.print();     //再次输出  
        return 0;  
    }  


--------------------- 

来源:CSDN 
原文:https://blog.csdn.net/yhdyy123/article/details/78393453 

在这里插入图片描述

这里是引用

#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;
}
--------------------- 
来源:CSDN 
原文:https://blog.csdn.net/yhdyy123/article/details/78393453 

当上面的代码被编译和执行时,它会产生下列结果:

Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值