C ++ 指针 | this指针_2

this指针

C ++有一个名为 "this" 的指针。"this" 返回自己的地址。

在某些情况下,"this" 可能是必要的,但经常使用它被认为是一种风格偏好。

请注意下面的程序,比较 Shape 自身区域的面积 和 shape 的面积:

 //Use 'this' to compare areas
 //The class functions
      int compareWithThis(Shape shape) 
      {
         //return the area of the calling shape
         return this->Area() > shape.Area(); 
      }
//Using the class function in a program
   //In this case sh1.Area() is being compared to sh2.Area()

   if(sh1.compareWithThis(sh2)) {
      cout << "\nShape2 is smaller than Shape1" <<endl;
   } 

 我可以执行完全相同的函数 而 不使用 " this " 。

//'this' is not necessary to compare shapes
      int compare(Shape shapeIn) 
      {
         return Area() > shapeIn.Area();
      }

要使用类函数:

 if(sh1.compare(sh2)) 
   {
      cout << "\nShape2 is smaller than Shape1" <<endl;
   } 

 举例,同样,该函数将sh1.area() 与 sh2.area()的进行比较。

#include <iostream>
 
using namespace std;

class Shape {
   public:
      // Constructor definition
      Shape(int l = 2, int w = 2) 
      {
         length = l;
         width = w;
      }
		
      double Area() 
      {
         return length * width;
      }
		
	  //Use 'this' to compare areas
      int compareWithThis(Shape shape) 
      {
         return this->Area() > shape.Area();
      }

      //'this' is not necessary to compare shapes
      int compare(Shape shapeIn) 
      {
         return Area() > shapeIn.Area();
      }
      
   private:
      int length;     // Length of a box
      int width;
};

int main(void) 
{
   Shape sh1(4, 4);    // Declare shape1
   Shape sh2(2, 6);    // Declare shape2

   if(sh1.compare(sh2)) 
   {
      cout << "\nShape2 is smaller than Shape1" <<endl;
   } 
   else 
   {
      cout << "\nShape2 is equal to or larger than Shape1" <<endl;
   }

   if(sh1.compareWithThis(sh2)) {
      cout << "\nShape2 is smaller than Shape1" <<endl;
   } 
   else 
   {
      cout << "Shape2 is equal to or larger than Shape1" <<endl;
   }
   
   return 0;
}

 运行结果:

代码解析:

1。以下代码中,this->Area() 是什么意思呢?

      //Use 'this' to compare areas
      int compareWithThis(Shape shape) 
      {
         return this->Area() > shape.Area();
      }

我们先来看 " -> " 和 " . " 的区别:

" -> " 是指针类型,是指针引用;

" . "   是实例化对象,类中普通成员的引用;

我们举个小例子:

class student
{

public:       
    string name[20];
};

第一种情况,采用指针访问 student *xy,则访问时,需要写成 *xy.name="hhhhh"; 等价于 xy->name="hhhhh";

第二种情况,采用普通成员访问 student xy,则访问时,需要写成 xy.name="hhhhh";

所以,this 代表 *Shape,整个式子来看,this.Shape->Are() 代表 :*Shape.Are() 。

这里 this.Shape->Are()  的值就是:2 * 2 = 4;

解析完毕。


编程就是算法和数据结构,算法和数据结构是编程的灵魂。 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值