初始化槽构造函数一个二维指针

时间:2018-05-15 15:01:14

标签: pointers multidimensional-array constructor

我创建了一个类,并尝试在类构造函数中初始化一个2D指针。然后我在main.cpp中使用了一个getter,但它没有用。构建成功但我在调试时最终得到值0xcccccccc?。 这是我的代码。

标题

Asset {
    public:

    Asset(int numberAssets, int numberReturns); // Constructor
    //getter and setter
    double **getAssetReturnMatrix();

    ~Asset();

private:
    int _numberAssets, _numberReturns;
    double **_assetReturn;
};

Cpp文件

#include "Asset.h"


Asset::Asset(int numberAssets, int numberReturns)
{
    // store data
    _numberAssets = numberAssets; // 83 rows  
    _numberReturns = numberReturns; // 700 cols

    //allocate memory for return matrix
    double **_assetReturn = new double*[_numberAssets]; // a matrix to  store the return data
    for (int i = 0; i<_numberAssets; i++)
        _assetReturn[i] = new double[_numberReturns];

}

Asset::~Asset()
{
}

Main.cpp的

#include <iostream>
#include "read_data.h"
#include "Asset.h"

using namespace std;
int  main(int  argc, char  *argv[])
{
    //Create our class object

    int numberAssets = 83;
    int numberReturns = 700;
    Asset returnMatrix = Asset(numberAssets, numberReturns);

    //read the data from the file and store it into the return matrix
    string fileName = "asset_returns.csv";
    double ** data = returnMatrix.getAssetReturnMatrix();

    cout << data; // <--- Value 0xcccccccc? here

    //readData(data, fileName);

    return 0;
}
你可以告诉我哪里错了吗? 非常感谢!

1 个答案:

答案 0 :(得分:0)

我创建了一个新变量,它与我的h文件中定义的私有成员double **_assetReturn无关,在这里:

//allocate memory for return matrix
double **_assetReturn = new double*[_numberAssets]; // a matrix to  store the return data
for (int i = 0; i<_numberAssets; i++)
    _assetReturn[i] = new double[_numberReturns];

将其更改为:

//allocate memory for return matrix
    this->_assetReturn = new double*[this->_numberAssets]; // a matrix to  store the return data
    for (int i = 0; i<this->_numberAssets; i++)
        this->_assetReturn[i] = new double[this->_numberReturns];

现在工作正常。