首页 > 编程语言 >C++ this 指针

C++ this 指针

时间:2023-03-23 23:56:41浏览次数:41  
标签:box Box double C++ 2.0 指针

在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。

因此,在成员函数内部,它可以用来指向调用对象。

友元函数没有 this 指针,因为友元不是类的成员。只有成员函数才有 this 指针。

下面的实例有助于更好地理解 this 指针的概念:

#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   5.94
   Box Box2(8.5, 6.0, 2.0);    // Declare box2   102
 
   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

  

 

 

 

参考资料:

C++ 中的 this 指针 | 菜鸟教程 (runoob.com)

标签:box,Box,double,C++,2.0,指针
From: https://www.cnblogs.com/xzit201802/p/17249950.html

相关文章

  • C++ 标准库 sort() / stable_sort() / partial_sort() 对比
    C++STL标准库中提供了多个用于排序的Sort函数,常用的包括有sort()/stable_sort()/partial_sort(),具体的函数用法如下表所示:函数用法std::sort(first,last)......
  • what's the difference between const and constexpr in C++?
    BothconstandconstexprareusedtodefineconstantsinC++,buttheyhavedifferentmeaningsandusecases.constisusedtodeclareavariableasconstant,......
  • Loops in C++
    #include<iostream>usingnamespacestd;intmain(){intv[]={0,1,2,3,4};for(autox:v){cout<<x<<endl;}for(autoy:......
  • when should we use struct in C++?
    InC++,structisakeywordusedtodefineadatastructurethatgroupsmultiplevariablesofdifferentdatatypesintoasingleunit.Herearesomesituations......
  • 指针与链表
    指针与链表各位CTFer可以忽略这篇文章~各位CTFer可以忽略这篇文章~各位CTFer可以忽略这篇文章~指针指针的定义指针对于变量来讲就像单人间的宿舍号一样。每个人(变量......
  • what are the primitive types of C++?
    InC++,thereareseveralprimitivedatatypes,whicharealsoknownasfundamentalorbuilt-indatatypes.Theseinclude:Integertypes:Usedtorepresentw......
  • how to learn C++?
    HerearesomestepstolearnC++:Learnthebasics:StartwiththebasicsofC++,includingvariables,datatypes,controlstructures,loops,andfunctions.......
  • C++ 内存池技术初探
    目录内存池意义单线程内存池全局函数new(),delete()局限性版本1:专用Rational内存管理器版本2:固定大小对象的内存池版本3:单线程可变大小内存管理器MemoryChunk内存块列表类......
  • C++中std::function常见用法
    C++标准库中的std::function是一个通用的函数封装,可以用来存储、复制、调用任何可调用对象(函数、函数指针、成员函数指针、lambda表达式等)。以下是std::function的一些常见......
  • 【C++入门】命名空间、缺省参数、函数重载
    前言在正式进入C++之前,我们首先要对C++有一个基本的认知。这里我就不过多的进行描述了,有兴趣的可以去网络搜索一番。总而言之,从名称上面我们也可以看得出来,C++是在C的基础上......