C++ c+中动态数组的Getter+;不起作用

C++ c+中动态数组的Getter+;不起作用,c++,boost,multidimensional-array,C++,Boost,Multidimensional Array,我在我的一个类中使用了boost的动态数组,但很难为它编写正确的getter函数。以下是我尝试的内容(我检查了类setter中的数组大小,并使用主函数中的getter): #包括 #包括“boost/multi_array.hpp” 使用名称空间std; 使用名称空间boost; typedef多_阵列3i; 课堂测试{ 私人: 阵列3i测试u阵列u; void init(整数x,整数y,整数z){ array3i测试_数组_u(区段[x][y][z]); coutgetter正在工作,但您没有

我在我的一个类中使用了boost的动态数组,但很难为它编写正确的getter函数。以下是我尝试的内容(我检查了类setter中的数组大小,并使用主函数中的getter):

#包括
#包括“boost/multi_array.hpp”
使用名称空间std;
使用名称空间boost;
typedef多_阵列3i;
课堂测试{
私人:
阵列3i测试u阵列u;
void init(整数x,整数y,整数z){
array3i测试_数组_u(区段[x][y][z]);

coutgetter正在工作,但您没有初始化成员

    array3i test_array_(extents[x][y][z]);
初始化局部变量(在
init()退出后停止存在)

有问题的部分是(可能)您不能只分配不同大小/形状的多数组。因此您需要使用
resize()
(或在构造函数初始值设定项列表中初始化
test\u数组
形状)

固定的:

#include <iostream>
#include "boost/multi_array.hpp"

using namespace std;
using namespace boost;

typedef multi_array<int, 3> array3i;

class Test {
  private:
    array3i test_array_;

    void init(int const x, int const y, int const z)
    {
        test_array_.resize(extents[x][y][z]);
        cout << "Size should be: " << test_array_.size() << endl;
        for (int j = 0; j < x; j++) {
            for (int jj = 0; jj < y; jj++) {
                for (int jjj = 0; jjj < z; jjj++) {
                    test_array_[j][jj][jjj] = j + jj + jjj;
                }
            }
        }
    };

  public:
    array3i test_array() { return test_array_; };

    Test(int x, int y, int z) { init(x, y, z); };
};

int main()
{
    Test test(2, 3, 5);

    cout << "Size from getter: " << test.test_array().size() << endl;
}
#包括
#包括“boost/multi_array.hpp”
使用名称空间std;
使用名称空间boost;
typedef多_阵列3i;
课堂测试{
私人:
阵列3i测试u阵列u;
void init(int const x,int const y,int const z)
{
测试数组大小(范围[x][y][z]);

cout问题可能是您有两个
test\u array
变量:一个作为类成员在类中,一个在
init
函数中


局部变量会隐藏和覆盖成员变量。

在init函数中,您应该具有:

void init(int const x, int const y, int const z)
{
    //test_array_.resize(extents[x][y][z]);
    test_array_ = array3i(extents[x][y][x]); 
    cout << "Size should be: " << test_array_.size() << endl;
    for (int j = 0; j < x; j++) {
        for (int jj = 0; jj < y; jj++) {
            for (int jjj = 0; jjj < z; jjj++) {
                test_array_[j][jj][jjj] = j + jj + jjj;
            }
        }
    }
}
void init(int const x,int const y,int const z)
{
//测试数组大小(范围[x][y][z]);
测试数组=数组3i(区段[x][y][x]);

你的“麻烦”是什么?怎么回事?请详细说明。我的错,我忘了下划线。不是这样。你可以:核心转储
void init(int const x, int const y, int const z)
{
    //test_array_.resize(extents[x][y][z]);
    test_array_ = array3i(extents[x][y][x]); 
    cout << "Size should be: " << test_array_.size() << endl;
    for (int j = 0; j < x; j++) {
        for (int jj = 0; jj < y; jj++) {
            for (int jjj = 0; jjj < z; jjj++) {
                test_array_[j][jj][jjj] = j + jj + jjj;
            }
        }
    }
}