构造一个空矩阵

Construct an empty matrix

本文关键字:一个      更新时间:2023-10-16

我有一个类

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;
}

问题是我如何编写一个构造函数来创建我可以使用的矩阵?

你的构造函数就是

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;
}

你的问题听起来像:如何将参数保存到常量行/列属性中。

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; };

在构造函数的参数列表中,参数按声明顺序初始化,因此不能使用行/列(它们尚未初始化)。

你需要一个指向指针的指针来创建 [普通] 二维数组所以

int ** const e;

然后构造函数可以像这样工作:

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

您的下一个问题是"如何初始化常量"。为此,您可以参考此处的答案:如何在类C++中初始化常量成员变量

要实现这一点,请将初始化器代码放在一个函数中:

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) {
}

以下是使用模板实现矩阵的另一种方法:

#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;
}

更短更干净。

要使注释行正常工作,必须向类中添加以下 2 个函数:

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;
};