我知道如果我想在 C++ 的类命名空间中使用 const 数组,我不能这样做:
class c
{
private:
struct p
{
int a;
int b;
};
static const p pp[2];
};
const c::p pp[2] = { {1,1},{2,2} };
int main(void)
{
class c;
return 0;
}
我必须做的:
class c
{
public:
struct p
{
int a;
int b;
};
static const p pp[2];
};
const c::p pp[2] = { {1,1},{2,2} };
int main(void)
{
class c;
return 0;
}
但这要求“p”和“pp”是公开的,而我希望它们是私有(private)的。在 C++ 中没有办法初始化私有(private)静态数组吗?
编辑:-------------------- 感谢您的回答。另外我希望这个类是一个库,只有头文件,供主项目使用。当被多个文件包含时,包含以下初始化程序会导致“多重定义”错误。
const c::p c::pp[2] = { {1,1},{2,2} };
我该如何解决这个问题?
最佳答案
您的第一个代码片段运行良好。您只需要将其更改为:
const c::p c::pp[2] = { {1,1},{2,2} };
关于c++ - C++ 类中的静态常量初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4605058/