#include using namespace std; class Box { public: // 构造函数定义 Box(double l, double b, double h) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // 每次创建对象时增加 1 objectCount++; } double Volume() { return length * breadth * height; } // 静态成员函数即使在类对象不存在的情况下也能被调用 // 静态函数只要使用类名加范围解析运算符 :: 就可以访问。 // 静态成员函数只能访问静态数据成员,不能访问其他静态成员函数和类外部的其他函数。 // 静态成员函数有一个类范围,他们不能访问类的 this 指针。 // 可以使用静态成员函数来判断类的某些对象是否已被创建。 static int getCount() { return objectCount; } private: double length; // 长度 double breadth; // 宽度 double height; // 高度 static int objectCount; }; // 初始化类 Box 的静态成员 int Box::objectCount = 0; int main(void) { Box Box1(3.3, 1.2, 1.5); // 声明 box1 Box Box2(8.5, 6.0, 2.0); // 声明 box2 // 输出对象的总数 cout << "Total objects: " << Box::getCount() << endl; return 0; }