2011-01-11 22 views

回答

6

數組的數組是從指針的數組,以陣列不同。在你的情況下,如果沒有你的數組的寬度(y)在你的公共接口中發佈,你將無法返回正確的類型。否則,編譯器不知道返回數組的每一行的寬度。

你可以嘗試以下方法:

class Sample 
{ 
public: 
    static const int x = 8; 
    static const int y = 10; 
    typedef char Row[y]; 
    Row *get2D(); 

private: 
    char two_d[x][y]; 
}; 
0

好得多會做到這一點:

const char& operator()(int x1, int y1) 
{ 
    // Better to throw an out-of-bounds exception, but this is illustrative. 
    assert (x1 < x); 
    assert (y1 < y); 
    return two_d[x][y]; 
}; 

這可以讓你安全的只讀訪問您的陣列內部(可檢查的!)。

+0

甚至更​​好的是隻使用Boost Matrix庫! http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm – EmeryBerger 2011-01-11 01:00:13