[英]How to declare new private variables from constructor?
I want to pass 2-dimensional arrays with different sizes to my class and store the arrays as private member variables. 我想将具有不同大小的二维数组传递给我的类,并将数组存储为私有成员变量。
When I try to declare the array in the constructor I get an error. 当我尝试在构造函数中声明数组时,出现错误。
How should I declare a private variable from constructor? 我应该如何从构造函数声明私有变量?
If it is not possible, what else can I do to make my class flexible for different array sizes? 如果不可能,我该怎么做才能使我的班级灵活地适应不同的数组大小?
Here is the header file: 这是头文件:
#ifndef NUMCPP_H
#define NUMCPP_H
class numcpp
{
public:
numcpp(int *Arr,int *Shape,int Dims);
private:
int *shape;
int dims;
};
#endif
Here is the source file: 这是源文件:
#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);
};
};
};
Classes must have a compile time fixed size, so a true flexible array member isn't possible. 类必须具有编译时固定的大小,因此不可能有真正的灵活数组成员。 The best you could do is either:
您能做的最好的是:
std::vector<std::vector<int>>
to get something functionally similar (runtime dynamically chosen size); std::vector<std::vector<int>>
这样的可动态调整大小的类型来获得功能上类似的东西(运行时动态选择的大小); the class itself remains fixed size, with the vector
storing the dynamically allocated arrays on the free store (heap). vector
将动态分配的数组存储在免费存储区(堆)上。 One implementation approach would look something like this (adding a declaration of std::vector<std::vector<int>> array;
in the private
section of the class declaration): 一种实现方法如下所示(在类声明的
private
部分中添加std::vector<std::vector<int>> array;
的声明):
// 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];
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.