我們可以使用static關(guān)鍵字定義類(lèi)的靜態(tài)成員。當(dāng)我們聲明一個(gè)類(lèi)的成員為靜態(tài)它意味著無(wú)論有多少的類(lèi)的對(duì)象被創(chuàng)建,有靜態(tài)成員只有一個(gè)副本。
靜態(tài)成員是由類(lèi)的所有對(duì)象共享。所有靜態(tài)數(shù)據(jù)被初始化為零,創(chuàng)建所述第一對(duì)象時(shí),如果沒(méi)有其他的初始化存在。我們不能把它的類(lèi)的定義,但它可以在類(lèi)的外部被初始化為通過(guò)重新聲明靜態(tài)變量做在下面的示例中,使用范圍解析運(yùn)算符::來(lái)確定它屬于哪個(gè)類(lèi)。
讓我們?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
通過(guò)聲明一個(gè)函數(shù)成員為靜態(tài)的,把它獨(dú)立于類(lèi)的任何特定對(duì)象。靜態(tài)成員函數(shù)可以被調(diào)用,即使存在的類(lèi)的任何對(duì)象和靜態(tài)函數(shù)使用類(lèi)名和作用域解析運(yùn)算符::訪(fǎng)問(wèn)。
靜態(tài)成員函數(shù)只能訪(fǎng)問(wèn)靜態(tài)數(shù)據(jù)成員,其他的靜態(tài)成員函數(shù),并從類(lèi)以外的任何其他功能。
靜態(tài)成員函數(shù)有一個(gè)類(lèi)范圍,他們沒(méi)有進(jìn)入這個(gè)指針之類(lèi)的??梢允褂靡粋€(gè)靜態(tài)成員函數(shù)來(lái)判斷是否已創(chuàng)建或不是類(lèi)的一些對(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