我想将不同大小的二维数组传递给我的类并将数组存储为私有成员变量。
当我尝试在构造函数中声明数组时,出现错误。
我应该如何从构造函数声明私有变量?
如果不可能,我还能做些什么来使我的班级灵活适应不同的数组大小?
这是头文件:
#ifndef NUMCPP_H
#define NUMCPP_H
class numcpp
{
public:
numcpp(int *Arr,int *Shape,int Dims);
private:
int *shape;
int dims;
};
#endif
这是源文件:
#include <iostream>
#include "numcpp.h"
using namespace std;
numcpp::numcpp(int *Arr,int *Shape,int Dims) // *arr points to input array's first element
{
shape = Shape;
dims = Dims;
int i = shape[0];
int j = shape[1];
int numcpp::array[i][j]; // error happens in this line
//assigning input array to our variable
for (int x = 0; x < i; x++)
{
for (int y = 0; y < j; y++)
{
array[x][y] = *(arr + (x * i) + y);
};
};
};
类必须有一个编译时固定的大小,所以一个真正灵活的数组成员是不可能的。你能做的最好的事情是:
std::vector<std::vector<int>>
来获得功能相似的东西(运行时动态选择的大小);类本身保持固定大小,vector
将动态分配的数组存储在空闲存储(堆)上。一种实现方法看起来像这样(在类声明std::vector<std::vector<int>> array;
的private
部分添加一个声明):
// Use initializers to initialize directly instead of default initializing, then replacing
numcpp::numcpp(int *arr,int *Shape,int Dims) : shape(Shape), dims(Dims), array(shape[0], std::vector<int>(shape[1]))
{
int i = shape[0];
int j = shape[1];
for (int c = 0; c < i * j; ++c) {
array[c / j][c % j] = arr[c];
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句