C++ 如何从构造函数声明新的私有变量?
我想将不同大小的二维数组传递给我的类,并将数组存储为私有成员变量 当我试图在构造函数中声明数组时,我得到一个错误 我应该如何从构造函数声明私有变量 如果不可能,我还能做些什么使我的类灵活地适应不同的数组大小 以下是头文件:C++ 如何从构造函数声明新的私有变量?,c++,C++,我想将不同大小的二维数组传递给我的类,并将数组存储为私有成员变量 当我试图在构造函数中声明数组时,我得到一个错误 我应该如何从构造函数声明私有变量 如果不可能,我还能做些什么使我的类灵活地适应不同的数组大小 以下是头文件: #ifndef NUMCPP_H #define NUMCPP_H class numcpp { public: numcpp(int *Arr,int *Shape,int Dims); private: int *shape; int dims;
#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);
};
};
};
以下是源文件:
#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);
};
};
};
#包括
#包括“numcpp.h”
使用名称空间std;
numcpp::numcpp(int*Arr,int*Shape,int-Dims)//*Arr指向输入数组的第一个元素
{
形状=形状;
dims=dims;
int i=形状[0];
int j=形状[1];
int numcp::array[i][j];//此行发生错误
//将输入数组分配给变量
对于(int x=0;x
类必须具有编译时固定大小,因此不可能有真正灵活的数组成员。您所能做的最好是:
std::vector
,以获得功能相似的内容(运行时动态选择大小);类本身保持固定大小,向量将动态分配的数组存储在空闲存储(堆)上private
部分添加std::vector array;
声明):
//使用初始值设定项直接初始化,而不是默认初始化,然后替换
numcpp::numcpp(int*arr,int*Shape,int-Dims):形状(Shape),Dims(Dims),数组(Shape[0],std::vector(Shape[1]))
{
int i=形状[0];
int j=形状[1];
对于(int c=0;c
@user7935991:我在主代码块前面的括号中提到了这一点。只需在private
部分添加必要的array
声明即可。您应该服用std::vector
药丸来消除头痛。