使用对象指针访问运算符重载函数

accessing operator overload functions using object pointer

我正在从 https://isocpp.org/wiki/faq/operator-overloading

实施这个 class
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

(*m)(i,j) 应该可以解决问题。但是你也可以实现一个等效的 at 方法,这样你就可以写 m->at(i,j).