簡體   English   中英

試圖使矩陣類起作用

[英]Trying to make a matrix class work

我的教授給了我們矩陣類的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 ++中分配2d數組。

然后,您可以將i,j元素訪問為[i*rows+j]

但是您應該覆蓋T & operator () (int,int)

不要忘記析構函數並delete[]

更改:

element = new T [rows][cols];

至:

element = new T [rows*cols];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM