簡體   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