带有运算符重载的C++矩阵类

gru*_*zip 2 c++ operators

我正在实现一个小的密集矩阵类,而不是计划get/set运算符,我想使用运算符重载来使API更加可用和连贯.

我想要实现的非常简单:

template<typename T>
class Matrix
{
public:

    /* ... Leaving out CTOR and Memory Management for Simplicity */

    T operator() (unsigned x, unsigned y){/* ... */ }
};


Matrix<int> m(10,10);
int value = m(5,3); // get the value at index 5,3
m(5,3) = 99; // set the value at index 5,3
Run Code Online (Sandbox Code Playgroud)

虽然通过重载直接获得价值operator(),但我无法理解定义setter.根据我的理解,运算符优先级将operator()在赋值之前调用,但是不能重载operator()以返回正确的左值.

解决这个问题的最佳方法是什么?

Ker*_* SB 8

我争辩说"做出正确的事情是不可能的":

struct Matrix
{
  int & operator()(size_t i, size_t j) { return data[i * Cols + j]; }
  const int & operator()(size_t i, size_t j) const { return data[i * Cols + j]; }

  /* ... */

private:
  const size_t Rows, Cols;
  int data[Rows * Cols];  // not real code!
};
Run Code Online (Sandbox Code Playgroud)

现在你可以说m(2,3) = m(3,2) = -1;等等