追蹤
積你耳屎喔低~GeNIuSoD
關於部落格
  • 10882

    累積人氣

  • 0

    今日人氣

    0

    追蹤人氣

static class member

例 1: static data member 的定義 
        class CTest{
        public:
                CTest(){}
                ~CTest(){}
              static int constructNum;
                int value;

        private:
              static int destructNum;
        }

 

一個 static data member 起始值 的設定 必須在 class 定義及 函數的 implementation 之外, 如例 2。

例 2: static data member 起始值 的設定 
        class CTest{
        public:
                CTest(){constructNum++;}
                ~CTest(){destructNum++;}
               static int constructNum;
                int value;
                int getDestructorNum(){ return destructNum;}

        private:
               static int destructNum;
        };

       int CTest::constructNum=0;
       int CTest::destructNum=0;

        main()
        {
        }

 

一個 public static data member 就如同 C 程式中 的一個全域變數,其引用方式, 即將 變數之前加上 class 的標示, 如下:

        CTest:: constructNum

例 3: public static data member 的引用
        class CTest{
        public:
                CTest(){constructNum++;}
                ~CTest(){destructNum++;}
               static int constructNum;
                int value;
                int getDestructorNum(){ return destructNum;}

        private:
               static int destructNum;
        };
       
       int CTest::constructNum=0;
 
       int CTest::destructNum=0;

        class CB{
        public:
                CB(){}
                ~CB(){}
                void set(){x = CTest::constructNum;}
                int get(){ return x;}

        private:
                int x;
        };

        main()
        {
                CTest t1, t2, *pt;
                CB b;

                b.set();
                cout<< "number of constructed class CTest = ";
                cout<< CTest::constructNum<< endl;
                cout<< "number of destructed class CTest = ";
                cout<< t1.getDestructorNum()<< endl;
                cout<< "b.x = "<< b.get()<< endl;

                pt = new CTest;
                b.set();
                cout<< "number of constructed class CTest = ";
                cout<< CTest::constructNum<< endl;
                cout<< "number of destructed class CTest = ";
                cout<< t1.getDestructorNum()<< endl;
                cout<< "b.x = "<< b.get()<< endl;
                delete pt;

                cout<< "number of constructed class CTest = ";
                cout<< CTest::constructNum<< endl;
                cout<< "number of destructed class CTest = ";
                cout<< t1.getDestructorNum()<< endl;
}

說明:
  1. 於 class CB 中亦可引用全域變數 CTest::constructNum, 該變數宣告的位置 在 引用處之前。
  2. 於 main() 中亦可引用全域變數 CTest::constructNum
相簿設定
標籤設定
相簿狀態