C++类中的静态成员
#include <iostream>using namespace std;class Box{ public: static int objectCount; // 构造函数定义 Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // 每次创建对象时增加 1 objectCount++; } double Volume() { return length * breadth * height; } private: double length; // 长度 double breadth; // 宽度 double height; // 高度};// 初始化类 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::objectCount << endl; return 0;}
C++中的静态成员函数,保证静态成员不被外部更改
#include <stdio.h>class Test{private: static int cCount;public: Test() { cCount++; } ~Test() { --cCount; } static int GetCount() { return cCount; }};int Test::cCount = 0;int main(){ printf("count = %d\n", Test::GetCount()); Test t1; Test t2; printf("count = %d\n", t1.GetCount()); printf("count = %d\n", t2.GetCount()); Test* pt = new Test(); printf("count = %d\n", pt->GetCount()); delete pt; printf("count = %d\n", Test::GetCount()); return 0;}结果 count = 0count = 2count = 2count = 3count = 2
C++中const修饰静态成员
#include <iostream>#include <stdio.h>class Test{private: const static int cCount;public: static int GetCount() { return cCount; }};const int Test::cCount = 100;int main(){ printf("count = %d\n", Test::GetCount()); return 0;}