2016-11-26 79 views
0

我正在編寫使用線程乘法矩陣的程序。我有填充動態int數組(不能使用向量)問題。C++填充動態數組int

CPP文件:HPP文件的

Matrix::Matrix(int n, int m) 
{ 
    mac_ = new int[n * m]; 
} 

Matrix::Matrix(std::istream & is) 
{ 
    int tmp; 
    int i = 0; 
    is >> m_; //rows 
    is >> n_; //columns 

    Matrix(n_, m_); // using 1st constructor 

    while (is.peek() != EOF) { 
     is >> tmp; 
     mac_[i] = tmp; // debug stop here 
     i++; 
    } 
} 

部分:

private: 
    int n_; // columns 
    int m_; // rows 
    int *mac_; 

從調試,我得到:

這0x0079f7b0 {N_ = 3 M_ = 2 MAC_ = 00000000 { }}

我知道我可以在第二個構造函數中編寫mac_ = new int(n_*m_);,但我想知道爲什麼1st不起作用。

+0

「Using 1st ..」創建一個臨時對象,而不是預期對象的分配 – Jonas

+0

您可以使用委託構造函數 – Jonas

+0

@Jonas他不能使用委託構造函數,因爲他首先必須使用'istream'爭取獲得施工參數。好的舊''init'函數在這裏更適合 – wasthishelpful

回答

2
// ... 

Matrix(n_, m_); // using 1st constructor 

while (is.peek() != EOF) { 
    is >> tmp; 
    mac_[i] = tmp; // debug stop here 
    i++; 
} 

看起來你覺得調用構造函數構造這裏的實際對象(this),然後你訪問它的成員屬性mac_

事實上,像你一樣調用構造函數會創建一個與此矩陣無關的其他對象(因爲您沒有將它存儲在變量中,它在行尾處被破壞)。

因此,因爲您構建了其他對象而不是this,this->mac_未初始化,因此您的錯誤。

修改你的代碼是這樣的:

Matrix::Matrix(int n, int m) 
{ 
    init(n, m); 
} 

Matrix::Matrix(std::istream & is) 
{ 
    int tmp; 
    int i = 0; 
    is >> m_; //rows 
    is >> n_; //columns 

    init(n_, m_); 

    while (is.peek() != EOF) { 
     is >> tmp; 
     mac_[i] = tmp; // debug should not stop here anymore 
     i++; 
    } 
} 

void Matrix::init(int n, int m) 
{ 
    mac_ = new int[n * m]; 
} 

注:這裏我拿出inititialization在功能init(也許應該是一個私有方法),以避免重複代碼。