目录

一个类的静态成员(Static members of a class)

我们可以使用static关键字定义类成员static 。 当我们将类的成员声明为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

静态功能成员

通过将函数成员声明为static,可以使其独立于类的任何特定对象。 即使没有类的对象存在,也可以调用静态成员函数,并且仅使用类名和范围解析运算符::来访问static函数。

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

静态成员函数具有类作用域,并且它们无权访问该类的this指针。 您可以使用静态成员函数来确定是否已创建类的某些对象。

让我们尝试以下示例来理解静态函数成员的概念 -

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 
↑回到顶部↑
WIKI教程 @2018