美文网首页
1.2.08_C++ this 指针

1.2.08_C++ this 指针

作者: 资深小夏 | 来源:发表于2017-06-29 21:06 被阅读9次

C++ 类 & 对象

在 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
   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

代码链接:https://github.com/karst87/cpp/tree/master/learning/com.runoob

相关文章

  • 1.2.08_C++ this 指针

    C++ 类 & 对象 在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员...

  • 混淆知识点

    1、指针数组&数组指针、常量指针&指针常量、函数指针&指针函数 数组指针&指针数组 数组指针的定义 int (*p...

  • C语言

    C 指针、指针变量、函数指针、指针函数、指针数组、数组指针、C 数组

  • 指针

    普通指针指针的指针 数组指针 函数指针

  • 函数指针

    概念: 指针函数, 函数指针, 指针数组, 数组指针, 指向数组的指针, 指向函数指针数组的指针。

  • C:函数指针的坑

    关于该死的函数指针和指针函数 先来个目录 常量指针、指针常量 数组指针、指针数组 函数指针、指针函数 1、先看第一...

  • C 语言指针

    指针类型:指针的读取长度,指针的读取方向(大小端) 空指针,无类型指针,野指针 常量指针,指向常量的指针 http...

  • 二、C语言基础

    A、指针 指针的概念:指针变量 和 指针 的区别 ?答:指针变量是指针的标记,也可以通过指针变量的标记操作指针内存...

  • 王道程序员求职宝典(十一)指针与引用,树

    指针与引用 指针声明typedef别名类型检查void*指针指向指针的指针函数指针typedef简化函数指针定义初...

  • NDK02

    指针 指针概念 1 .指针变量和指针的区别?答: 指针变量是定义指针的标记,指针就是指向的内存地址。2 .函数指针...

网友评论

      本文标题:1.2.08_C++ this 指针

      本文链接:https://www.haomeiwen.com/subject/dqpvcxtx.html