类的数据成员有两种一是存在在类类型的每个对象中的葡萄成员,还有一个是独立于类的任意对象存在,属于类的,不与类对象关联,这种称为static成员。
对于特定类型的全体对象而言,有时候可能需要访问一个全局的变量
- # ifndef _COUNTOBJECT_H_
- # define _COUNTOBJECT_H_
- class CountObject
- {
- public:
- CountObject(void);
- ~CountObject(void);
- static int count_;
- };
- # endif
- # include "CountObject.h"
- # include <iostream>
- //静态成员定义说明,此时就不需要加static了
- int CountObject::count_ = 0;
- CountObject::CountObject()
- {
- ++count_;
- }
- CountObject::~CountObject()
- {
- --count_;
- }
- # include "CountObject.h"
- # include <iostream>
- using namespace std;
- int main(void)
- { //静态成员属于类,被所有对象共享
- //因为是公有的所以可以直接访问
- cout << CountObject::count_<<endl;
- CountObject col;
- cout << CountObject::count_<<endl;
- return 0;
- }
- # ifndef _TEST_H_
- # define _TEST_H_
- class Test
- {
- public:
- Test(int y_);
- ~Test();
- void TestFun();
- static void TestStaticFun();
- public:
- static const int x_ ;
- int y_;
- };
- # endif //_TEST_H_
- #include "Test.h"
- # include <iostream>
- using namespace std;
- Test::Test(int y):y_(y)
- {
- }
- Test::~Test(void)
- {
- }
- void Test::TestFun()
- {//非静态成员函数可以访问静态成员
- cout<<"x = " << x_<<endl;
- cout<<"This is not a static fun but it can call StaticFun()..." <<endl;
- }
- void Test::TestStaticFun()
- {
- //cout<<"y = "<<y_<<endl; error,static成员函数不能访问非静态成员
- //因为没有this指针,指向某个对象,而y属于某个对象,因为无法访问非静态成员
- // TestFun(); error ,静态成员函数不能调用非静态成员函数
- //因为需要传递this指针,而静态成员函数没有this指针
- }
- const int Test::x_ = 100;
- # include "Test.h"
- # include <iostream>
- using namespace std;
- int main(void)
- {
- cout << Test::x_ <<endl;
- Test t(10);
- t.TestFun();
- cout << t.y_ << endl; //cout << t::x_<<endl; static 不能被对象调用,只能由类调用
- //cout<<t.x<<endl; 不推荐这样使用
- cout <<Test::x_ << endl; //x是属于类的static成员
- return 0;
- }


















