类的静态成员

我们可以使用static关键字定义类的静态成员。当我们声明一个类的成员为静态它意味着无论有多少的类的对象被创建,有静态成员只有一个副本。

静态成员是由类的所有对象共享。所有静态数据被初始化为零,创建所述第一对象时,如果没有其他的初始化存在。我们不能把它的类的定义,但它可以在类的外部被初始化为通过重新声明静态变量做在下面的示例中,使用范围解析运算符::来确定它属于哪个类。

让我们试试下面的例子就明白了静态数据成员的概念:

import std.stdio;

class Box
{
   public:
      static int objectCount = 0;
      // Constructor definition
      this(double l=2.0, double b=2.0, double h=2.0)
      {
         writeln("Constructor called.");
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

void main()
{
   Box Box1 = new Box(3.3, 1.2, 1.5);    // Declare box1
   Box Box2 = new Box(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   writeln("Total objects: ",Box.objectCount);

}
当上面的代码被编译并执行,它会产生以下结果:
Constructor called.
Constructor called.
Total objects: 2

静态函数成员:

通过声明一个函数成员为静态的,把它独立于类的任何特定对象。静态成员函数可以被调用,即使存在的类的任何对象和静态函数使用类名和作用域解析运算符::访问。

静态成员函数只能访问静态数据成员,其他的静态成员函数,并从类以外的任何其他功能。

静态成员函数有一个类范围,他们没有进入这个指针之类的。可以使用一个静态成员函数来判断是否已创建或不是类的一些对象。

让我们试试下面的例子就明白了静态成员函数的概念:

import std.stdio;

class Box
{
   public:
      static int objectCount = 0;
      // Constructor definition
      this(double l=2.0, double b=2.0, double h=2.0)
      {
         writeln("Constructor called.");
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      static int getCount()
      {
         return objectCount;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};


void main()
{

   // Print total number of objects before creating object.
   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

   // Print total number of objects after creating object.
   writeln("Final Stage Count: ",Box.getCount());
}

让我们编译和运行上面的程序,这将产生以下结果:

Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3