static成员变量又称为静态成员变量,在多个对象间共享使用,并且static静态变量在初始化时必须在类外初始化,可以直接通过“类名::变量”访问,哪怕是还没有生成对象时一样可以访问,以此看来static成员变量不隶属于某个对象,而隶属于类,只是所有该类的对象都可以使用而已。
另外,静态的成员函数不在于多个对象之间的信息共享,而是在于管理类内的static数据成员,完成对static数据成员的封装。
示例图:
#include <iostream> using namespace std; class CStatic { public: CStatic(int l, int w) { length = l; width = w; } static void set_height() { // 静态函数操作静态成员,静态函数没有this指针 height = 20; } int show_box() { return length * width * height; } private: int length; int width; static int height; }; // 在类外初始化 int CStatic::height = 0; int main(int argc, char* argv[]) { CStatic s1(2, 5); CStatic s2(3, 9);; // s1 对象修改了共享的 height 的值 // s2 对象中 height 的值也同时被修改了 s1.set_height(); cout << s1.show_box() << endl; cout << s2.show_box() << endl; getchar(); return 0; }