头文件中的C/C++私有数组初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/520893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C/C++ private array initialization in the header file
提问by Milan
I have a class called Cal and it's .cpp and .h counterpart
我有一个叫做 Cal 的类,它是 .cpp 和 .h 对应的
Headerfile has
头文件有
class Cal {
private:
int wa[2][2];
public:
void do_cal();
};
.cpp file has
.cpp 文件有
#include "Cal.h"
void Cal::do_cal() {
print(wa) // where print just itterates and prints the elements in wa
}
My question is how do I initialize the array wa
? I just can't seem to get it to work.
我的问题是如何初始化数组wa
?我似乎无法让它发挥作用。
I tried with :
我试过:
int wa[2][2] = {
{5,2},
{7,9}
};
in the header file but I get errors saying I cant do so as it's against iso..something.
在头文件中,但我收到错误,说我不能这样做,因为它反对 iso..something。
Tried also to initialize the array wa
in the constructor but that didnt work either.. What am I missing ?
还尝试wa
在构造函数中初始化数组,但这也不起作用..我错过了什么?
Thanks
谢谢
回答by Rob K
If it can be static, you can initialize it in your .cpp file. Add the static keyword in the class declaration:
如果它可以是静态的,则可以在 .cpp 文件中对其进行初始化。在类声明中添加 static 关键字:
class Cal {
private:
static int wa[2][2];
public:
void do_cal();
};
and at file scope in the .cpp file add:
并在 .cpp 文件的文件范围内添加:
#include "Cal.h"
int Cal::wa[2][2] = { {5,2}, {7,9} };
void Cal::do_cal() {
print(wa) // where print just itterates and prints the elements in wa
}
If you never change it, this would work well (along with making it const). You only get one that's shared with each instance of your class though.
如果你从不改变它,这会很好地工作(同时使它成为常量)。但是,您只能获得与类的每个实例共享的一个。
回答by Perchik
You cannot initialize array elements in a class declaration. I recently tried to find a way to do just that. From what I learned, you have to do it in your initialize function, one element at a time.
您不能在类声明中初始化数组元素。我最近试图找到一种方法来做到这一点。根据我的了解,您必须在 initialize 函数中执行此操作,一次一个元素。
Cal::Cal{
wa[0][0] = 5;
wa[0][1] = 2;
wa[1][0] = 7;
wa[1][1] = 9;
}
It's possible (and probable) that there's a much better way to do this, but from my research last week, this is how to do it with a multi dimensional array. I'm interested if anyone has a better method.
有可能(并且很可能)有更好的方法来做到这一点,但从我上周的研究来看,这是如何使用多维数组来做到这一点。如果有人有更好的方法,我很感兴趣。
回答by Adam Rosenfield
You can't do it easily. If you don't want to specify each element individually like in Perchik's answer, you can create one static array and memcpy
that (which will probably be faster for non-trivial array sizes):
你不能轻易做到。如果您不想像 Perchik's answer那样单独指定每个元素,您可以创建一个静态数组memcpy
(对于非平凡的数组大小可能会更快):
namespace
{
const int default_wa[2][2] = {{5, 2}, {7, 9}};
}
Cal::Cal
{
memcpy(&wa[0][0], &default_wa[0][0], sizeof(wa));
}