パブリック列挙型とその列挙型のプライベート静的メンバー変数を持つクラスを作成しようとしています。静的変数の値を初期化できますが、クラス メンバー関数でアクセスしようとすると、コードがリンクしません。コンパイルする簡単な作業例を次に示します。
g++ -o TestClass.o TestClass.cpp
しかし、メインソースファイルをコンパイル/リンクしようとすると失敗します:
g++ -o test TestClass.o testmain.cpp
私が得るエラーは次のとおりです。
Undefined symbols for architecture x86_64:
"TestClass::_enum", referenced from:
TestClass::printEnum() in TestClass.o
ld: symbol(s) not found for architecture x86_64
OSX 10.7.5、gcc 4.2.1 を実行している Mac を使用しています。
TestClass.h:
#ifndef TEST_CLASS_H
#define TEST_CLASS_H
class TestClass
{
public:
TestClass() {};
void printEnum();
typedef enum {A, B, C} MyEnum;
private:
static MyEnum _enum;
};
#endif
TestClass.cpp:
#include "TestClass.h"
#include <iostream>
using namespace std;
TestClass::MyEnum _enum = TestClass::A;
void TestClass::printEnum()
{
cout << "Value of enum: " << _enum << endl;
}
testmain.cpp:
#include "TestClass.h"
int main()
{
TestClass tc;
tc.printEnum();
}