類的靜態成員

我們可以使用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