我正在從https://isocpp.org/wiki/faq/operator-overloading實作這個類
class Matrix {
public:
Matrix(unsigned rows, unsigned cols);
double& operator() (unsigned row, unsigned col); // Subscript operators often come in pairs
double operator() (unsigned row, unsigned col) const; // Subscript operators often come in pairs
// ...
~Matrix(); // Destructor
Matrix(const Matrix& m); // Copy constructor
Matrix& operator= (const Matrix& m); // Assignment operator
// ...
private:
unsigned rows_, cols_;
double* data_;
};
inline
Matrix::Matrix(unsigned rows, unsigned cols)
: rows_ (rows)
, cols_ (cols)
//, data_ ← initialized below after the if...throw statement
{
if (rows == 0 || cols == 0)
throw BadIndex("Matrix constructor has 0 size");
data_ = new double[rows * cols];
}
inline
Matrix::~Matrix()
{
delete[] data_;
}
inline
double& Matrix::operator() (unsigned row, unsigned col)
{
if (row >= rows_ || col >= cols_)
throw BadIndex("Matrix subscript out of bounds");
return data_[cols_*row col];
}
inline
double Matrix::operator() (unsigned row, unsigned col) const
{
if (row >= rows_ || col >= cols_)
throw BadIndex("const Matrix subscript out of bounds");
return data_[cols_*row col];
}
在我的主程式中,我宣告
Matrix *m = new Matrix(20,20)
現在如何訪問元素?一般
Matrix m(20,20)
會做的作業。但是在另一種情況下如何訪問?我試過
*m(i,j) - didn't work
m->operator()(i,j) - didn't work
uj5u.com熱心網友回復:
(*m)(i,j)應該做的伎倆。但是你也可以實作一個等效的at方法,這樣你就可以撰寫m->at(i,j).
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314974.html
