繁体   English   中英

如何从构造函数声明新的私有变量?

[英]How to declare new private variables from constructor?

我想将具有不同大小的二维数组传递给我的类,并将数组存储为私有成员变量。

当我尝试在构造函数中声明数组时,出现错误。

我应该如何从构造函数声明私有变量?

如果不可能,我该怎么做才能使我的班级灵活地适应不同的数组大小?

这是文件:

#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);
        };
    };
};

类必须具有编译时固定的大小,因此不可能有真正的灵活数组成员。 您能做的最好的是:

  1. 在数组维度上对类进行模板化(选择固定大小的编译时间)
  2. 使用像std::vector<std::vector<int>>这样的可动态调整大小的类型来获得功能上类似的东西(运行时动态选择的大小); 类本身保持固定大小, vector将动态分配的数组存储在免费存储区(堆)上。

一种实现方法如下所示(在类声明的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM