If you encounter a pen question: design a matrix class, input the rows and columns through the constructor, and support the [] [] values and values.
This is actually a two-dimensional array subscript operator overload problem, the solution is as follows:
(1) Use a one-dimensional array instead of a two-dimensional array to allocate memory to obtain continuous memory space. When the value is calculated, the values of the corresponding rows and columns are obtained.
(2) design two classes: Reload operator [], one to get rows and one to get columns.
The implementation is as follows:
Code
Class matrixentry {
Friend class matrix; // you can access the private variable m_currentrow.
Public:
Matrixentry (int m, int N): m_row (M), m_col (N)
{
M_pmatrix = new int [M * n * sizeof (INT)];
}
~ Matrixentry ()
{
Delete m_pmatrix;
}
Int & operator [] (INT col)
{
Return m_pmatrix [m_currentrow * m_col + Col];
}
PRIVATE:
Int * m_pmatrix; // One-dimensional array of the storage matrix
Int m_row; // number of rows in the Matrix
Int m_col; // Number of columns in the Matrix
Int m_currentrow; // specifies the row to be accessed. The value is set by the matrix class below.
};
Class matrix {
Public:
Matrix (int m, int N): m_entry (m, n)
{
}
Matrixentry & operator [] (INT row)
{
M_entry.m_currentrow = row;
Return m_entry;
}
PRIVATE:
Matrixentry m_entry;
};
Test:
Test code
Int x = 1;
Int I;
Matrix M (5, 5 );
For (I = 0; I <5; I ++)
{
For (Int J = 0; j <5; j ++)
{
M [I] [J] = x ++;
}
}
For (I = 0; I <5; I ++)
{
For (Int J = 0; j <5; j ++)
{
Cout <m [I] [J] <Endl;
}
}
the above implementation only takes into account the most basic functions, and does not involve the error handling logic such as subscript out-of-bounds. If you are interested, you can complete it. If you want to design a generic class, replace int with T in template .