简体   繁体   中英

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:

  1. Templating the class on the array dimensions (compile time chosen fixed size)
  2. Using a dynamically resizable type like std::vector<std::vector<int>> to get something functionally similar (runtime dynamically chosen size); the class itself remains fixed size, with the vector storing the dynamically allocated arrays on the free store (heap).

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):

// 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];
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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