D语言 中的 this指针函数

首页 / D语言入门教程 / D语言 中的 this指针函数

D语言中的每个对象都可以通 this 访问自己的指针地址, this 指针是所有成员函数的隐式参数。

让我们尝试以下示例以了解 this 指针的概念-

import std.stdio;

class Box { 
   public: 
      //构造函数定义
      this(double l=2.0, double b=2.0, double h=2.0) { 
         writeln("Constructor called."); 
         length=l;
         breadth=b; 
         height=h; 
      }
         
      double Volume() { 
         return length * breadth * height; 
      }

      int compare(Box box) { 
         return this.Volume() > box.Volume(); 
      }

   private: 
      double length;     //长
      double breadth;    //宽
      double height;     //高
}
  
void main() { 
   Box Box1=new Box(3.3, 1.2, 1.5);    //实例化box1
   Box Box2=new Box(8.5, 6.0, 2.0);    //实例化box2
   
   if(Box1.compare(Box2)) { 
      writeln("Box2 is smaller than Box1"); 
   } else { 
      writeln("Box2 is equal to or larger than Box1"); 
   }
}

编译并执行上述代码后,将产生以下输出-

无涯教程网

Constructor called. 
Constructor called. 
Box2 is equal to or larger than Box1

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

零基础学Python -〔尹会生〕

10x程序员工作法 -〔郑晔〕

Spring Boot与Kubernetes云原生微服务实践 -〔杨波〕

罗剑锋的C++实战笔记 -〔罗剑锋〕

实用密码学 -〔范学雷〕

编程高手必学的内存知识 -〔海纳〕

深入剖析Java新特性 -〔范学雷〕

大厂广告产品心法 -〔郭谊〕

深入浅出可观测性 -〔翁一磊〕

好记忆不如烂笔头。留下您的足迹吧 :)