C++之過載陣列下標[]與圓括號()運算子的方法
阿新 • • 發佈:2019-01-10
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix(int, int) ;
int& operator()(int, int) ; // 過載圓括號運算子"()"
private:
int * m_nMatrix ;
int m_nRow, m_nCol ;
};
Matrix::Matrix(int nRow, int nCol)
{
m_nRow = nRow ;
m_nCol = nCol ;
m_nMatrix = new int[nRow * nCol] ;
for(int i = 0 ; i < nRow * nCol ; ++i)
{
*(m_nMatrix + i) = i ;
}
}
//過載圓括號運算子"()":
int& Matrix::operator()(int nRow, int nCol)
{
return *(m_nMatrix + nRow * m_nCol + nCol) ; //返回矩陣中第nRow行第nCol列的值
}
//測試程式碼:
int main()
{
Matrix mtx(10, 10) ; //生成一個矩陣物件aM
cout << mtx(3, 4) << endl ; //輸出矩陣中位於第3行第4列的元素值
mtx(3, 4) = 35 ; //改變矩陣中位於第3行第4列的元素值
cout << mtx(3, 4) << endl ;
system("Pause") ;
return 0 ;
}