簡體   English   中英

static 公共成員 function ( C++ )

[英]static public member function ( C++ )

我需要計算我的公共成員 function 在循環中創建新數據的次數。 每次讀取數據時,都會將其保存到私有成員變量中。 沒有任何內容被覆蓋。

// my classType.h
const int ImpliedIndex = 1000;

class classType
{
private:
  char privateMember[ImpliedIndex];
  char privateMember2[ImpliedIndex];
public:
  static void myMemberCounter;
  void printMyInformation():
  void mySupplier(const char[] );
  ...
};

//classType.cpp
int globalCounter = 0;

void classType::printMyInformation()
{
   ...
   cout << privateMember << endl;
   cout << globalCounter++ << endl;
}
void classType::mySupplier( const char buff[] )
{
   strcpy( privateMember, buff );

}

// The main should clear things up a bit.
// main.cpp

int main()
{
    while ( !inFile.eof() )
    {   
        for ( int x = 0; x < 20; x++ )
        {
       // do file I/O here
       // save each line of file into an temp array
       // supply temp array with a routine defined in myClass
       // re-use temp array until we run out of file
        }
    }    
//close file

我需要將我的 20 更改為變量。 請注意,在 classType 中,我使用 globalCounter 來檢索類型的數量。

我想做的是, globalCounter = memberCounter;

但是我必須重新聲明這兩個變量,並且不能將myClass[ImpliedIndex].memberCounter與賦值運算符 (=) 或二進制插入運算符 (<<) 一起使用。

這一行:

static void myMemberCounter;

應該生成編譯時錯誤。 它看起來像一個變量,但類型為void ,這沒有意義。

如果你想要一個 static (“類變量”)計數器,你應該使用像int這樣的類型。 然后,class 很容易使用該計數器來計算實例數,只需在構造函數中遞增計數器即可。 外部世界可以通過添加一個public的 class function 來讀取計數以返回它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM