- D 程式設計基礎
- D 程式設計 - 首頁
- D 程式設計 - 概述
- D 程式設計 - 環境
- D 程式設計 - 基本語法
- D 程式設計 - 變數
- D 程式設計 - 資料型別
- D 程式設計 - 列舉
- D 程式設計 - 字面量
- D 程式設計 - 運算子
- D 程式設計 - 迴圈
- D 程式設計 - 條件語句
- D 程式設計 - 函式
- D 程式設計 - 字元
- D 程式設計 - 字串
- D 程式設計 - 陣列
- D 程式設計 - 關聯陣列
- D 程式設計 - 指標
- D 程式設計 - 元組
- D 程式設計 - 結構體
- D 程式設計 - 聯合體
- D 程式設計 - 範圍
- D 程式設計 - 別名
- D 程式設計 - 混入
- D 程式設計 - 模組
- D 程式設計 - 模板
- D 程式設計 - 不可變
- D 程式設計 - 檔案 I/O
- D 程式設計 - 併發
- D 程式設計 - 異常處理
- D 程式設計 - 合約
- D - 條件編譯
- D 程式設計 - 面向物件
- D 程式設計 - 類與物件
- D 程式設計 - 繼承
- D 程式設計 - 過載
- D 程式設計 - 封裝
- D 程式設計 - 介面
- D 程式設計 - 抽象類
- D 程式設計 - 有用資源
- D 程式設計 - 快速指南
- D 程式設計 - 有用資源
- D 程式設計 - 討論
D 程式設計 - 類的靜態成員
我們可以使用 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
靜態函式成員
透過將函式成員宣告為靜態,使其獨立於類的任何特定物件。即使不存在類的任何物件,也可以呼叫靜態成員函式,並且靜態函式只能使用類名和作用域解析運算子 :: 來訪問。
靜態成員函式只能訪問靜態資料成員、其他靜態成員函式以及類外部的任何其他函式。
靜態成員函式具有類作用域,並且無法訪問類的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
d_programming_classes_objects.htm
廣告