2016-08-26 9 views
0

私は、自分のクラスのインスタンスの総数を保持するpublic staticメンバを宣言しました。次のようにコードは次のとおりです。public static変数メンバにアクセスできない

class Hello { 
public: 
    static int myCount; 
    void test(){ 
     //do nothing 
    }; 
    Hello(){ 
     Hello::myCount += 1; 
    }; 
    ~Hello() { 
     Hello::myCount -= 1; 
    } 
}; 

int main(int argc, const char * argv[]) { 
    // insert code here... 
    Hello *p1 = new Hello();p1->test(); 
    Hello *p2 = new Hello();p2->test(); 
    cout << Hello::myCount; 

    return 0; 
} 

しかし、Iコンパイル、それは言う:

Undefined symbols for architecture x86_64: 
    "Hello::myCount", referenced from: 
     _main in main.o 
     Hello::Hello() in main.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

私が間違っているところ私にはわかりません。最後にC++で作業してから数年が経ちましたので、解決策をお勧めしますか? ありがとうございます。

+1

クラス定義外で定義します。 'int Hello :: myCount;' – songyuanyao

答えて

2

静的メンバは、例えば、クラスの外で定義する必要があります。ここでは

class Hello { 
public: 
    static int myCount; 
    void test(){ 
     //do nothing 
    }; 
    Hello(){ 
     Hello::myCount += 1; 
    }; 
    ~Hello() { 
     Hello::myCount -= 1; 
    } 
}; 

int Hello::myCount = 0; // definition outside of the class 

(...) 

は、それはあなたの問題を解決するのに役立ちますことを、示すための例です:http://ideone.com/LVXVCc

ので、それがすべてです1つの定義ルールと呼ばれるルール。
静的クラスメンバhereのコンテキストで、これについて詳しく読むことができます。

要約:static int myCount宣言はメンバーの定義ではありません。クラスは通常、.h/.hppヘッダーファイルに格納され、他の多くのファイルに含まれています。それらが静的メンバーを含み、上記のような行が定義である場合、それは複数定義エラーにつながります。

これを防ぐために、この宣言は定義として扱われないため、後で定義する必要があります。

+0

また、クラスのインスタンスをカウントすることも意図しているので、値を初期化することをお勧めします。 – Aziuth

+0

@Aziuth、私は注意を払っていないが、もちろん、はい。 – 5208760

+0

別のファイルでは、 'int Hello :: myCount = 999;を定義します。 '、その後何が起こる – lenhhoxung

関連する問題