Reputation: 1281
I'm trying to write a class with a public enum, and a private static member variable of that enum type. I can initialise the value of the static variable, but if I try to access it in a class member function, my code won't link. Here's a simple working example that will compile with:
g++ -o TestClass.o TestClass.cpp
but then fails when I try to compile/link the main source file with:
g++ -o test TestClass.o testmain.cpp
The error I get is:
Undefined symbols for architecture x86_64:
"TestClass::_enum", referenced from:
TestClass::printEnum() in TestClass.o
ld: symbol(s) not found for architecture x86_64
I'm using a Mac running OSX 10.7.5, with gcc 4.2.1.
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();
}
Upvotes: 2
Views: 4433
Reputation: 3397
Static member outside class is not defined properly proper format: classname::enumtype staticmember = value;
in your example it is TestClass::MyEnum _enum = TestClass::A;
Upvotes: 0
Reputation: 19032
The code below declares a file local variable _enum
of type TestClass::MyEnum
. It is not providing the definition for your static member variable.
TestClass::MyEnum _enum = TestClass::A;
To do that, you have to specifically define it in the appropriate class scope, like this:
TestClass::MyEnum TestClass::_enum = TestClass::A;
Upvotes: 3