静态const初始化结构C ++类中的数组 [英] Static Const Initialised Structure Array in C++ Class
问题描述
我知道如果我想在C ++中的类命名空间中的const数组,我不能这样做:
I understand if I want a const array in a class namespace in C++ I cannot do:
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希望他们是私人的。 C ++中没有办法初始化私有静态数组?
But this requires "p" and "pp" to be public, when I want them to be private. Is there no way in C++ to initialise private static arrays?
编辑:-------------------
感谢您的答案。另外我想这个类是一个库,只有头文件,供一个主项目使用。在包含多个文件时,包括以下初始化程序导致多重定义错误。
------------------- Thanks for the answers. In addition I want this class to be a library, header files only, for use by a main project. Including the following initialiser results in " multiple definition of " errors when included by multiple files.
const c::p c::pp[2] = { {1,1},{2,2} };
我如何解决这个问题?
推荐答案
您的第一个代码段工作正常。您只需将其更改为:
Your first code snippet works fine. You just need to change it to:
const c::p c::pp[2] = { {1,1},{2,2} };
这篇关于静态const初始化结构C ++类中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!