gpt4 book ai didi

c++ - 试图使矩阵类工作

转载 作者:行者123 更新时间:2023-11-28 07:08:08 25 4
gpt4 key购买 nike

我的教授给了我们一个矩阵类的 C++ 实现,但我无法让它工作。

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

在我的 cpp 文件中,我正在创建一个矩阵对象,如下所示:

matrix<int> m1(2,2);

但是,我不断收到以下错误:

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]; 你不能在 C++ 中分配二维数组。

然后你可以访问 i,j 元素作为 [i*rows+j]

但是你应该覆盖 T & operator () (int,int)

不要忘记析构函数和delete[]

关于c++ - 试图使矩阵类工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21452515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com