[英]Initialize const multidimensional array in class initializer list from constructor arguments
I have a class that includes a const 2d array of values, and I want to define this array when I call the constructor. 我有一个包含const 2d数组值的类,我想在调用构造函数时定义这个数组。 I have been told using
const
on values that should never be changed is preferred, so I wanted to try it in this case. 我被告知使用
const
值,永远不应该更改,所以我想在这种情况下尝试。
class A {
public:
A(const int passedArray[2][2]) : memberArray(passedArray) {}
private:
const int memberArray[2][2];
};
const int passedArray[][2] = {
{0,0},
{0,1}
};
A a(passedArray); // fails with "incompatible types
//in assignment of 'const int (*)[2]' to 'const in[2][2]'
A a(&passedArray); // fails
This also fails with const int passedArray[2][2] = ...
, with private: const int** memberArray
, etc. 这也失败了
const int passedArray[2][2] = ...
, private: const int** memberArray
等。
I know I have to use an initializer list because a constructor cannot change values of const. 我知道我必须使用初始化列表,因为构造函数不能更改const的值。 Is this possible at all on C++11?
这在C ++ 11上是否可行?
Comments to your question has some good info. 对您的问题的评论有一些很好的信息。
After that here is the working code: 之后是这里的工作代码:
//g++ 5.4.0
#include <iostream>
class A {
public:
A(int passedArray[2][2])
{
//USE STD COPY TO COPY THE ARRAYS.
std::copy(&passedArray[0][0], &passedArray[0][0]+4,&memberArray[0][0]);
//PRINT VALUES TO TEST
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
std::cout << memberArray[i][j] << std::endl;
}
}
}
private:
int memberArray[2][2];
};
int main()
{
//INITIALIZE YOUR ARRAY
int passedArray[2][2] = {
{0,0},
{0,1}
};
//CREATE OBJECT
A a(passedArray);
}
If your business need is to have a "const multi dimensional array in your class" you have to do it any one of the below ways. 如果您的业务需要在您的班级中拥有“const多维数组”,则必须采用以下任何一种方法。
class A {
public:
A(const int passedArray[2][2])
{
}
private:
const int memberArray[2][2] = {{5,6},{7,8}}; //INITIALIZE HERE
};
OR 要么
class A {
public:
A(const int passedArray[2][2])
{
}
private:
//DECLARE STATIC HERE
static const int memberArray[2][2];
};
//INTIALIZE HERE
const int A::memberArray[2][2] = {{5,6},{7,8}};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.