静态成员

来源:互联网 发布:落叶知多少是哪首诗 编辑:程序博客网 时间:2024/06/05 10:37
#include<iostream>using namespace std;class A{    public:        A()        {            cout<<"A()"<<endl;            count++;        }        ~A()        {            cout<<"~A()"<<endl;            count--;        }        void out()//非静态成员方法        {            cout<<"count:"<<count<<endl;//非静态成员方法可以引用静态成员        }        static int getCount() //静态成员方法        {            //cout<<x<<endl;//error,静态成员方法不能引用非静态成员            return count;        }    private:        int x;        static int count;//静态成员变量声明,可以完全脱离对象而存在};//静态成员变量必须要初始化,并且要在类外初始化int A::count; //默认为0void main(){       //A a1;    //    ////既然创建出了对象实例,count就不可能为0,矛盾     //if(a1.getCount() == 0)    //{    //    //}/*  //只有在count是public情况下使用      if(A::count == 0)    {        cout<<"count\n";    }*/    if(0 == A::getCount())    {        cout << A::getCount << ", " << A::getCount();    }}

单例模式

#include<iostream>using namespace std;class Sun{public:    //2. 通过公有方法创建出对象,并且通过私有属性curSun保证每次都创建出来的都赋值给同一个对象    //3. 为了避免矛盾(要创建一个对象,必须通过对象的getSun方法,而调用getSun方法,必须要依赖一个对象),加上static属性就可以脱离对象而存在了    static Sun *getSun()    {        if (NULL == curSun)            curSun = new Sun();        return curSun;    }private:    //1.1 构造函数私有化    Sun()        :isShining(false)//静态成员变量不能在初始化列表中初始化    {        cout << "Sun()" << endl;    }    //1.2 拷贝构造函数私有化    Sun(const Sun &sun)    {        cout << "Sun(const Sun &sun)" << endl;    }    //1.3 赋值构造函数私有化    Sun operator=(const Sun &sun)    {        cout << "Sun operator=(const Sun &sun)" << endl;    }    static bool isShining;    static Sun *curSun;};//静态成员变量必须要初始化Sun *Sun::curSun = NULL;//默认为NULLbool Sun::isShining;//默认为falsevoid main(){    //Sun s1,s2,s3;//error      Sun::getSun();    Sun::getSun();    Sun::getSun();}
原创粉丝点击