Jas*_*n S 7 c++ arrays constructor
我熟悉C++构造函数和初始化器:
class Foo {
int x;
public:
Foo(int _x) : x(_x) {}
};
Foo foo1(37);
Foo foo2(104);
Run Code Online (Sandbox Code Playgroud)
我的问题是我必须实现一个具有3x6数组成员的类.我将如何做与上述相似的事情?
class Bar {
int coeff[3][6];
public:
// what do I do for a constructor????
};
Run Code Online (Sandbox Code Playgroud)
编辑:对于一个普通的数组,我会做以下,我只是不知道如何为一个类做:
static int myCoeffs[3][6] =
{{ 1, 2, 3, 4, 5, 6},
{ 7, 8, 9, 10, 11, 12},
{ 13, 14, 15, 16, 17, 18}};
Run Code Online (Sandbox Code Playgroud)
编辑2:由于各种原因(例如,这是一个有限制的嵌入式系统)我不需要使用Boost,所以如果它提供了解决方案,我就无法使用它.
更新:我没有绑定初始化程序.可以在构造函数体中执行它,也不必是内联的.我只是在寻找一种正确的方法来构造一个需要系数数组的类的实例,而不会弄乱指针赋值.
你不能.在C++ 03中,您无法在ctor-initalization列表中初始化数组.但是你可以在构造函数体中完成它(技术上它不再是初始化).
那是
struct x
{
int a[4];
x():a({1,2,3,4}) //illegal
{
a[0] = 1;
etc.
}
};
Run Code Online (Sandbox Code Playgroud)
Edit: 经过问题编辑,这是一种方法
#include <algorithm>
struct x
{
int arr[3][4];
x(int (&arg)[3][4])
{
std::copy(&arg[0][0], &arg[0][0]+3*4, &arr[0][0]);
}
};
Run Code Online (Sandbox Code Playgroud)