我正在编写一个矩阵模板类,我遇到的问题是创建了数组并填充了值,但是当我使用 print() 函数时,数组再次为空。谁能指出我做错了什么?
数据定义如下:
T **data;
template<class T>
CMatrix<T>::CMatrix( int rows, int cols)
{
setRow(rows);
setCol(cols);
data = new int*[rows];
// Create matrix with dimensions given
for (int i = 0; i < row; i++) {
data[i] = new int [cols];
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < cols; j++) {
data[i][j] = (int) i * j;
}
}
}
template<class T>
void CMatrix<T>::print()
{
int i,j;
for (i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("%.1f ",data[i][j]);
}
printf("\n");
}
}
主功能:
int main (){
int rows =4;
int cols = 4;
CMatrix<int>* matrixOne= new CMatrix<int>(rows, cols);
matrixOne->print();
return(0);
}
模板声明:
template<class T>
class CMatrix
{
private:
int row; // number of rows
int column; // number of columns
public:
CMatrix(int rows, int cols);
CMatrix(const CMatrix& data); //Copy constructor
//Constructor taking an array of 16 elements
CMatrix(T Matrix[16]);
~CMatrix();
T **data;
void setRow(int r);
void setCol(int c);
int getRow();
int getCol();
//Subscript operators
T& operator()(int row, int col);
T operator()(int row, int col) const;
void print();
};