D语言 中的 类静态方法函数

首页 / D语言入门教程 / D语言 中的 类静态方法函数

让我们尝试以下示例以了解静态数据成员的概念-

import std.stdio;

class Box { 
   public: 
      static int objectCount=0;

      //构造函数定义
      this(double l=2.0, double b=2.0, double h=2.0) { 
         writeln("Constructor called."); 
         length=l; 
         breadth=b; 
         height=h; 
          
         //每次创建对象时增加
         objectCount++; 
      } 

      double Volume() { 
         return length * breadth * height; 
      }

   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  
   
   //打印对象总数。
   writeln("Total objects: ",Box.objectCount);  
}

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

Constructor called. 
Constructor called. 
Total objects: 2

静态函数

静态成员函数只能从类外部访问,让我们尝试以下示例以了解静态函数成员的概念-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-static-members.html

来源:LearnFk无涯教程网

import std.stdio;

class Box { 
   public: 
      static int objectCount=0; 
      
      //构造函数定义
      this(double l=2.0, double b=2.0, double h=2.0) { 
         writeln("Constructor called."); 
         length=l; 
         breadth=b; 
         height=h; 

         //每次创建对象时增加
         objectCount++; 
      }

      double Volume() {
         return length * breadth * height; 
      }

      static int getCount() { 
         return objectCount; 
      } 
   
   private: 
      double length;     //长
      double breadth;    //宽
      double height;     //高
};
  
void main() { 
   //在创建对象之前打印对象总数。
   writeln("Inital Stage Count: ",Box.getCount());  
   
   Box Box1=new Box(3.3, 1.2, 1.5);    //Declare box1 
   Box Box2=new Box(8.5, 6.0, 2.0);    //Declare box2 
   
   //创建对象后打印对象总数。
   writeln("Final Stage Count: ",Box.getCount()); 
} 

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

Inital Stage Count: 0 
Constructor called. 
Constructor called
Final Stage Count: 2 

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

技术教程推荐

ZooKeeper实战与源码剖析 -〔么敬国〕

OAuth 2.0实战课 -〔王新栋〕

重学线性代数 -〔朱维刚〕

代码之丑 -〔郑晔〕

大数据经典论文解读 -〔徐文浩〕

Web 3.0入局攻略 -〔郭大治〕

超级访谈:对话毕玄 -〔毕玄〕

Vue 3 企业级项目实战课 -〔杨文坚〕

手把手带你搭建推荐系统 -〔黄鸿波〕

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