C++ this pointer

本文介绍C++中this指针的概念及其使用方法,通过Box类的实例展示了如何利用this指针调用成员函数并比较两个对象的属性。

对于任何一个class,都有一个this pointer可以指代它,它可以指向这个class中的任何member functions,注意不包括friend functions

#include <iostream>
using namespace std;

class Box
{
   double width;
   public:
   Box(double wid):width(wid)
  {
     cout << "object is created" << endl;
  }
   double getwidth()
  {
      return width;
  }
   int comparef(Box box)
   {
     return this->getwidth() > box.getwidth();  // 也可以box.width(不管width作为private还是public,当box作为参数时,都可以用点)
   }
};


int main()
{
   Box box1(12),box2(13);
   if(box1.comparef(box2))                     //this is important
      cout << "box1 is bigger than box2";
   else 
      cout << "box1 is not bigger than box2";
    return 0;
    
   getvalue(box1);
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值