使用指针的c++自定义矩阵模板
c++ custom matrix template using pointers
这是我最近开始实现的一个矩阵模板。它没有很多函数,因为,就像我说的,我刚刚开始。
头文件:
#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.
没有初始化两个参数构造函数中的成员变量rows
和columns
。从它们的getter中获取一些垃圾值
Matrix(int rows, int columns) : rows(rows), columns(columns)
// ^^^^^^^^^^^^^^^^^^^^^^^^^ Add this
{
// ....
}
您忘记在一个构造函数中设置rows
和columns
成员变量。一种方法是使用赋值,但初始化成员变量的首选和更好的方法是使用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
构造函数的双形参版本。那个版本没有初始化rows
和columns
变量。
一个好的经验法则是,如果你得到了完全是垃圾的值,你忘记在某个地方将它们初始化为一个合理的值。
话虽这么说,我还是建议你选一本好的c++入门书籍,通读一遍。你得到的错误与变量的初始化有关,这是语言的一个非常基本的方面。
因为您没有在传递行和列的构造函数中初始化类的rows
和columns
成员。因此,它们包含来自内存的垃圾。
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];
}
}
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- std::ranges::elements_view,用于自定义类似元组的数据
- 跟随整数索引列表的自定义类迭代器
- 参数化自定义CMake工具链
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 如何在自定义类中启用'auto loops'?
- 使用QJsEngine在Qt中注册自定义类型
- Qt自定义QPush按钮未显示在布局上
- 自定义对象的dlib序列化在gcc中失败
- 自定义创建QFuture
- 如何在QT中的自定义视频小工具t上绘制矩形