2014-12-04 71 views
0

我有一個類構造一個空矩陣

class A 
{ 
    int *const e; 
    const int row, column; 
public: 
    A(int r, int c); // create a empty matrix with r rows and c columns passed in method 
} 

int main(int argc, char* argv[]) 
{ 
    A test(2,2); 
    return 0; 
} 

問題是,我該如何編寫創建,我可以用一個矩陣構造?

+0

,如果你想要的任何預置的矩陣功能,外觀到像徵 – chris 2014-12-04 01:48:00

+0

庫,但在這個項目中我不想使用任何庫 – Cieja 2014-12-04 01:49:26

+0

'memset'是你的朋友,假設你真的只想要一個「空」(這在軟件開發中沒有真正意義)矩陣。另外,由於「empty」這個詞出現在你的問題標題中,而不是在體內,所以我不知道你真正要求什麼。 – 2014-12-04 02:08:50

回答

0

你的問題聽起來像: 如何將參數保存到常量行/列屬性中。

A::A(int r, int c): row(r), column(c), e(new int[r*c]) 
{ 
    for (int i=0; i<r*c; i++) e[i]=0; 
} 

也不要忘記析構函數:

virtual ~A(){ delete[] e; }; 

在構造函數中的參數列表,參數在聲明的順序初始化,所以你不能使用行/列(它們尚未被初始化)。

1

你的構造也只是

A::A(int r, int c) : row{r}, column{c} 
{ 
    e = new int[r * c]; 
} 

那麼你的析構函數應該是

A::~A() 
{ 
    delete[] e; 
} 

,您可以訪問的元素

for (int i = 0; i < row; ++i) 
{ 
    for (int j = 0; j < column; ++j) 
    { 
     std::cout << e[i * row + j] << " "; // Using array arithmetic 
    } 
    std::cout << std::endl; 
} 
+0

e也是const。 – 2014-12-04 02:45:41

+0

錯誤錯誤C2758:'A :: e':引用類型的成員必須初始化 那麼我應該首先初始化變量嗎? – Cieja 2014-12-04 02:49:31

0

你需要一個指針的指針,以創建一個[普通] 2維數組 所以

int ** const e; 

然後構造函數可以工作,如:

e = (int**) malloc(sizeof(int**) * a); 
for(int i=0;i<a;++i) { 
    e[i] = (int*) malloc(sizeof(int*) * b); 
} 

你的下一個問題是「如何初始化常量「。對於這一點,你可以參考答案在這裏: how to initialize const member variable in a class C++

實現這一點,把inittializer代碼的函數:

initConstArray(const int** const a, int r, int c) { 
    e = (int**) malloc(sizeof(int**) * a); 
    for(int i=0;i<r;++i) { 
     e[i] = (int*) malloc(sizeof(int*) * b); 
     for(int j = 0;j < c; ++j) { 
     e[i][j] = a[i][j]; 
    } 

,並從構造函數初始化列表中調用這個函數:

A(int **a, int r, int c) : initConstArray(a, r, c) { 
} 
+0

malloc?我可能會考慮使用硬編碼指針而不是智能指針,但這對我來說太過分了。 – 2014-12-04 02:08:45

+0

請原諒我的代碼。這只是爲了概念上的解釋。 - 謝謝 – 2014-12-04 02:10:39

+0

只是開玩笑:-)但是,有更好的。 – 2014-12-04 02:11:38

0

這裏是用模板實現矩陣的另一種方式:

#include <array> 
#include <iostream> 

template <std::size_t ROW, std::size_t COLUMN> 
class A 
{ 
    std::array<int, ROW*COLUMN> a; 
public: 
    A():a(){}; 
}; 


int main(int argc, char* argv[]) 
{ 
    A<3,3> test; 
    //test.printSize(); 
    //std::cout << test; 
    return 0; 
} 

更短,更乾淨。

爲了使註釋行工作,你必須添加到類以下兩個功能:

void printSize(){ std::cout << ROW << "x" << COLUMN << std::endl; }; 

friend std::ostream& operator<<(std::ostream& os, A<R,C> mat){ 
    int col_count = 0; 
    for (auto id=mat.a.begin(); id!=mat.a.end(); id++){ 
     os << *id << (++col_count%C==0?"\n":" "); 
    } 

    return os; 
};