C++ const和static

来源:互联网 发布:幼儿园大班美工活动 编辑:程序博客网 时间:2024/05/19 10:07

const :

#include<iostream>using namespace std;class CFun{private:    static const int a=1;   //静态常量的变量(整型) 可以在类中直接初始化;public:    static int GetA()    {        return a;    }    void Show(/*      CFun *this =   const CFun &fun         */)    {        //a=2;        cout << a << endl;//非 常量函数可以用常量,但是不能改常量        cout << "void Show()" << endl;    }    void ShowShow(/*   const CFun *this  =     const CFun &fun           */)    const            //  不能修改类中的成员变量 因为 this 指针已经变成  const CFun*    {        cout << "const void ShowShow()" << endl;    }};int main(){    const CFun fun;//常量对象只能调用常函数。    //fun.Show(/*     const CFun &fun      */);     fun.ShowShow(/*     const CFun &fun      */);    CFun fun1;    fun1.Show();    cout << CFun::GetA() << endl;    system("pause");    return 0;}

static :

#include<iostream>using namespace std;class CFun{private:    static int nCount;  //定义了静态成员就要在类外初始化;    //int a;            //非静态变量public:    CFun()    {        nCount++;    }    ~CFun()    {        nCount--;    }public:    static int GetCount()    {        //a=1;  //a是非静态变量不能在静态成员函数中使用,因为静态成员没有this        return nCount;    }};//========初始化===========//int CFun :: nCount=0;//类型+类名+作用于运算符+静态变量=赋值;int main(){    //利用静态成员函数,可以不创建对象就调用类中成员;    cout << CFun ::GetCount() << endl;    CFun fun1;    CFun fun2;    //可以算出对象大小;    //cout << CFun ::nCount <<endl; 私有的所以要利用公共借口函数    cout << CFun ::GetCount() << endl;    system("pause");    return 0;}
0 0
原创粉丝点击