我們可以使用static關(guān)鍵字定義類的靜態(tài)成員。當(dāng)我們聲明一個(gè)類的成員為靜態(tài)它意味著無論有多少的類的對(duì)象被創(chuàng)建,有靜態(tài)成員只有一個(gè)副本。
靜態(tài)成員是由類的所有對(duì)象共享。所有靜態(tài)數(shù)據(jù)被初始化為零,創(chuàng)建所述第一對(duì)象時(shí),如果沒有其他的初始化存在。我們不能把它的類的定義,但它可以在類的外部被初始化為通過重新聲明靜態(tài)變量做在下面的示例中,使用范圍解析運(yùn)算符::來確定它屬于哪個(gè)類。
讓我們?cè)囋囅旅娴睦泳兔靼琢遂o態(tài)數(shù)據(jù)成員的概念:
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); }
當(dāng)上面的代碼被編譯并執(zhí)行,它會(huì)產(chǎn)生以下結(jié)果:
Constructor called. Constructor called. Total objects: 2
通過聲明一個(gè)函數(shù)成員為靜態(tài)的,把它獨(dú)立于類的任何特定對(duì)象。靜態(tài)成員函數(shù)可以被調(diào)用,即使存在的類的任何對(duì)象和靜態(tài)函數(shù)使用類名和作用域解析運(yùn)算符::訪問。
靜態(tài)成員函數(shù)只能訪問靜態(tài)數(shù)據(jù)成員,其他的靜態(tài)成員函數(shù),并從類以外的任何其他功能。
靜態(tài)成員函數(shù)有一個(gè)類范圍,他們沒有進(jìn)入這個(gè)指針之類的??梢允褂靡粋€(gè)靜態(tài)成員函數(shù)來判斷是否已創(chuàng)建或不是類的一些對(duì)象。
讓我們?cè)囋囅旅娴睦泳兔靼琢遂o態(tài)成員函數(shù)的概念:
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()); }
讓我們編譯和運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
Inital Stage Count: 0 Constructor called. Constructor called. Final Stage Count: 2