D 语言 - 类的静态成员
我们可以使用 static 关键字定义类成员static。 当我们将类的成员声明为静态时,意味着无论创建该类的多少个对象,都只有一份静态成员的副本。
静态成员由该类的所有对象共享。 如果没有其他初始化,则在创建第一个对象时,所有静态数据都将初始化为零。 您不能将其放在类定义中,但可以在类外部对其进行初始化,如以下示例所示,通过重新声明静态变量,使用作用域解析运算符 :: 来识别它属于哪个类。
让我们尝试下面的例子来理解静态数据成员的概念 −
import std.stdio;
class Box {
public:
static int objectCount = 0;
// 构造函数定义
this(double l = 2.0, double b = 2.0, double h = 2.0) {
writeln("Constructor called.");
length = l;
breadth = b;
height = h;
// 每次创建对象时增加
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
// 打印对象总数。
writeln("Total objects: ",Box.objectCount);
}
当上面的代码被编译并执行时,会产生以下结果 −
Constructor called. Constructor called. Total objects: 2
静态函数成员
通过将函数成员声明为静态,可以使其独立于类的任何特定对象。 即使类的对象不存在,也可以调用静态成员函数,并且仅使用类名和作用域解析运算符 :: 来访问静态函数。
静态成员函数只能访问静态数据成员、其他静态成员函数以及来自类外部的任何其他函数。
静态成员函数具有类作用域,并且它们无权访问类的 this 指针。 您可以使用静态成员函数来确定该类的某些对象是否已创建。
让我们尝试下面的例子来理解静态函数成员的概念 −
import std.stdio;
class Box {
public:
static int objectCount = 0;
// 构造函数定义
this(double l = 2.0, double b = 2.0, double h = 2.0) {
writeln("Constructor called.");
length = l;
breadth = b;
height = h;
// 每次创建对象时增加
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() {
// 创建对象之前打印对象总数。
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
// 创建对象后打印对象总数。
writeln("Final Stage Count: ",Box.getCount());
}
当上面的代码被编译并执行时,会产生以下结果 −
Inital Stage Count: 0 Constructor called. Constructor called Final Stage Count: 2
❮ d_programming_classes_objects.html

