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

静态函数

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

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 

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

技术教程推荐

邱岳的产品手记 -〔邱岳〕

程序员进阶攻略 -〔胡峰〕

趣谈Linux操作系统 -〔刘超〕

后端技术面试 38 讲 -〔李智慧〕

软件设计之美 -〔郑晔〕

分布式系统案例课 -〔杨波〕

流程型组织15讲 -〔蒋伟良〕

说透区块链 -〔自游〕

零基础实战机器学习 -〔黄佳〕

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