尝试使矩阵类工作 我的教授给我们C++实现了一个矩阵类,但是我很难让它工作。
尝试使矩阵类工作 我的教授给我们C++实现了一个矩阵类,但是我很难让它工作。,c++,arrays,matrix,C++,Arrays,Matrix,template<typename T> class matrix { public: matrix(int rows = 0, int cols = 0); matrix<T> operator+(const matrix<T>&); matrix<T> operator*(const matrix<T>&); matrix<T> transpose(const matri
template<typename T>
class matrix {
public:
matrix(int rows = 0, int cols = 0);
matrix<T> operator+(const matrix<T>&);
matrix<T> operator*(const matrix<T>&);
matrix<T> transpose(const matrix<T>&);
int rows;
int cols;
T* element;
};
template <typename T>
matrix<T>::matrix(int rows, int cols) {
//if rows or cols <0, throw exception
this->rows = rows;
this->cols = cols;
element = new T [rows][cols];
}
更改:
element = new T [rows][cols];
致:
该
元素=新的T[行][cols]代码>应该是element=newt[rows*cols]代码>不能在C++中分配2D数组。
然后您可以将i,j
元素作为[i*rows+j]
进行访问
但是您应该重写T&operator()(int,int)
不要忘记析构函数和删除[]
有些关联:这个实现的错误之一是没有严格遵守规则。你迟早会发现自己在追查撞车事件,直到问题得到解决。关于错误,C++不支持变量数组。您需要在单个序列中分配所有元素,并在寻址它们时自己进行偏移量计算。即元素=新的T[rows*cols]代码>@WhozCraig这不是完整的实现,它只是我认为相关的部分,因为我只是尝试先创建对象。这是我在VisualStudio上写的,但现在我更仔细地研究教授的实现,它实际上是T[rows*cols],我只是看错了!最终你会意识到它实际上应该是std::vector元素
和构造函数应该只在初始值设定项列表中包含元素(rows*cols)
(顺便说一下,您的行和cols
成员也属于该列表)。这解决了许多问题,包括免费为您提供RO3合规性,而无需您额外的工作。
non-constant expression as array bound
: while compiling class template member function 'matrix<T>::matrix(int,int)'
see reference to class template instantiation 'matrix<T>' being compiled
error C2440: '=' : cannot convert from 'int (*)[1]' to 'int *'
1> Types pointed to are unrelated; conversion requires reinterpret_cast,
C- style cast or function-style cast
m1.element[0] = 3;
m1.element[1] = 2;
m1.element[2] = 6;
m1.element[3] = 9;
element = new T [rows][cols];
element = new T [rows*cols];