我需要声明一个结构的类成员数组,这个结构理论上是在声明中初始化的,如下所示:
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...
};
这可以在传统的C ++(pre C ++ 11)类头中完成吗?
编辑:如果没有,那么什么是好的选择呢?将数组作为类成员是好的,但除此之外,它可以在公共头文件中定义。
答案 0 :(得分:4)
静态类变量以前必须在头文件之外的实现文件中初始化。
使用C ++ 11,如果静态类变量为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;
}
旧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;
}