Reputation: 17668
I need to declare a class member array of structs that is ideally initialized at declaration like this:
class Foo
{
typedef struct _TMember
{
uint16 m_key;
uint16 m_val;
}
TMember;
TMember m_member_tab[] =
{
{ 10, 2400},
{ 20, 2500},
{ 30, 2600},
{ 40, 2700},
{ 50, 2650},
};
// etc...
};
Can this be done in traditional C++ (pre C++11) class header?
Edit: If not, what would be a good alternative? It'd be good to have the array as a class member, but otherwise it can be defined in a common header file.
Upvotes: 3
Views: 2422
Reputation: 60067
Static class variables used to have to be initialized in the implementation file, outside of the header.
With C++11, in-class initialization works if the static class variables is constexpr
:
#include <iostream>
class Foo{
public:
struct TMember //can't start with an underscore; typedef unecessary in C++
{
unsigned short m_key;
unsigned short m_val;
};
constexpr static TMember m_member_tab[]={
{ 10, 2400},
{ 20, 2500},
{ 30, 2600},
{ 40, 2700},
{ 50, 2650},
};
};
int main()
{
using namespace std;
cout<<Foo::m_member_tab[1].m_val<<endl;
}
Old C++:
#include <iostream>
class Foo{
public:
struct TMember //can't start with underscore; typedef unecessary in C++
{
unsigned short m_key;
unsigned short m_val;
};
static TMember m_member_tab[5];
};
//End of header, start of implementation
Foo::TMember Foo::m_member_tab[] = {
{ 10, 2400},
{ 20, 2500},
{ 30, 2600},
{ 40, 2700},
{ 50, 2650},
};
int main()
{
using namespace std;
cout<<Foo::m_member_tab[1].m_val<<endl;
}
Upvotes: 5