让我们尝试以下示例以了解静态数据成员的概念-
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
参考链接
https://www.learnfk.com/d-programming/d-programming-static-members.html
标签:Box,breadth,教程,静态方法,double,无涯,height,objectCount,2.0 From: https://blog.51cto.com/u_14033984/8654954