使用指针的c++自定义矩阵模板

c++ custom matrix template using pointers

本文关键字:自定义 c++ 指针      更新时间:2023-10-16

这是我最近开始实现的一个矩阵模板。它没有很多函数,因为,就像我说的,我刚刚开始。

头文件:

#ifndef MATRIXX_H
#define MATRIXX_H
#include <iostream>
using namespace std;
template <typename theType> class Matrix
{
public:
Matrix()
{
    rows = columns = 0;
    matrixRoot = new theType *[rows];
    for(int i = 0; i < rows; i++)
    {
        matrixRoot[i] = new theType[columns];
    }
}
Matrix(int rows, int columns) 
{
    matrixRoot = new theType *[rows];
    for(int i = 0; i < rows; i++)
    {
        matrixRoot[i] = new theType[columns];
    }
}
~Matrix()
{
    delete [] *matrixRoot;
    delete [] matrixRoot;
}
int numrows() const
{
    return rows;
}
int numcols() const
{
    return columns;
}
private:
int rows;   
int columns;    
theType **matrixRoot;
};
#endif

当我尝试运行这个测试程序时,问题出现了:

#include "matrixx.h"
#include <iostream>
void TestingMatrix()
{
int r = 5;
int c = 4; 
Matrix<int> a(r, c);
cout << "Number of rows: " << a.numrows() << " Number of columns: " << a.numcols() << endl;
}
int main()
{
TestingMatrix();
}

如果它是正确的,我希望输出产生如下内容:

行数:5列数:4

相反,我得到了方式的东西:

行数:134515193列数:2515748

有趣的是,每次运行程序时,列的数量会改变,但行的数量不会改变。

显然,如果我甚至不能正确初始化矩阵的实例,我将无法得到任何地方,所以我想知道我做错了什么,给了我这样错误的结果。顺便说一句,我知道我的析构函数也搞砸了,因为它导致程序出现分段错误(lol),但这是一个问题,我计划在未来自己解决。如果有人能解释一下为什么我要得到行和列的这些数字,以及我如何才能让它返回正确的值,我真的很感激。

谢谢。(:

Matrix<int> a(r, c);  // Invokes constructor with arguments.

没有初始化两个参数构造函数中的成员变量rowscolumns。从它们的getter中获取一些垃圾值

Matrix(int rows, int columns) : rows(rows), columns(columns)
                               // ^^^^^^^^^^^^^^^^^^^^^^^^^ Add this
{
       // ....
}

您忘记在一个构造函数中设置rowscolumns成员变量。一种方法是使用赋值,但初始化成员变量的首选和更好的方法是使用ctor-initializer,如:

Matrix(int rows, int columns) : rows(rows), columns(columns)  
{ 
    matrixRoot = new theType *[rows]; 
    for(int i = 0; i < rows; i++) 
    { 
        matrixRoot[i] = new theType[columns]; 
    } 
} 

声明Matrix<int> a(r, c);调用Matrix构造函数的双形参版本。那个版本没有初始化rowscolumns变量。

一个好的经验法则是,如果你得到了完全是垃圾的值,你忘记在某个地方将它们初始化为一个合理的值。


话虽这么说,我还是建议你选一本好的c++入门书籍,通读一遍。你得到的错误与变量的初始化有关,这是语言的一个非常基本的方面。

因为您没有在传递行和列的构造函数中初始化类的rowscolumns成员。因此,它们包含来自内存的垃圾。

Matrix(int rows, int columns) 
{
    this->rows = rows;
    this->columns = columns;
    matrixRoot = new theType *[rows];
    for(int i = 0; i < rows; i++)
    {
        matrixRoot[i] = new theType[columns];
    }
}