2014-12-04 94 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; 
};