静态成员变量和静态成员函数
在 C++中,静态成员是属于整个类的而不是某个对象,静态成员变量只存储
一份供 所有对象共用。所以在所有对象中都可以共享它。使用静态成员变量实
现多个对象之间 的数据共享不会破坏隐藏的原则,保证了安全性还可以节省内
存。
类的静态成员,属于类,也属于对象,但终归属于类。
静态成员变量

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include<iostream>
using namespace std;
class Box { public: Box(); ~Box(); static int height; private:
int lenght; int width; };
int Box::height = 100;
Box::Box() { }
Box::~Box() { }
int main(char *argv[], int argc) { Box b; cout << b.height << endl; cout << Box::height << endl; return 0; }
|

静态成员函数

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include<iostream>
using namespace std;
class Box { public:
Box(); ~Box(); static int getHeight() { return height; } static int height; private:
int lenght; int width; };
int Box::height = 100;
Box::Box() { }
Box::~Box() { }
int main(char *argv[], int argc) { Box b; cout << b.height << endl; cout << Box::height << endl; cout << Box::getHeight() << endl; return 0; }
|


