【问题标题】:C++ overload operator [ ][ ]C++ 重载运算符 [ ][ ]
【发布时间】:2013-03-23 16:11:26
【问题描述】:

我有 CMatrix 类,其中是指向值数组的“双指针”。

class CMatrix {
public:
    int rows, cols;
    int **arr;
};

我只需要通过键入来访问矩阵的值:

CMatrix x;
x[0][0] = 23;

我知道如何使用:

x(0,0) = 23;

但我真的需要换一种方式。任何人都可以帮助我吗?请?

最后感谢大家的帮助,我是这样做的...

class CMatrix {
public:
   int rows, cols;
   int **arr;

public:
   int const* operator[]( int const y ) const
   {
      return &arr[0][y];
   }

   int* operator[]( int const y )
   {
      return &arr[0][y];
   }

   ....

感谢您的帮助,我真的很感激!

【问题讨论】:

  • C++中没有operator[][],你也编不出来...
  • “我真的需要这样做”为什么?是作业吗?
  • 只重载数组项的[]操作符
  • @BartekBanachewicz 因为这是学校作业,用精确的术语...

标签: c++ matrix overloading operator-keyword


【解决方案1】:

您不能重载operator [][],但这里的常见习惯用法是使用代理类,即重载operator [] 以返回具有operator [] 重载的不同类的实例。例如:

class CMatrix {
public:
    class CRow {
        friend class CMatrix;
    public:
        int& operator[](int col)
        {
            return parent.arr[row][col];
        }
    private:
        CRow(CMatrix &parent_, int row_) : 
            parent(parent_),
            row(row_)
        {}

        CMatrix& parent;
        int row;
    };

    CRow operator[](int row)
    {
        return CRow(*this, row);
    }
private:
    int rows, cols;
    int **arr;
};

【讨论】:

  • 您可能希望将CMatrix 类设为friendCRow 类,否则将无法构造CRow
【解决方案2】:

C++ 中没有operator[][]。但是,您可以重载 operator[] 以返回另一个结构,并且在该重载 operator[] 中也可以得到您想要的效果。

【讨论】:

    【解决方案3】:

    您可以通过重载operator[] 来返回int*,然后由[] 的第二个应用程序对其进行索引。除了int*,您还可以返回另一个代表行的类,其operator[] 可以访问行的各个元素。

    从本质上讲,operator[] 的后续应用会处理前一个应用的结果。

    【讨论】:

      【解决方案4】:

      如果您使用标准库容器创建矩阵,这很简单:

      class Matrix {
          vector<vector<int>> data;
      
      public:
          vector<int>& operator[] (size_t i) { return data[i]; }
      };
      

      【讨论】:

      • 因为这是学校作业我不能使用任何其他图书馆感谢 iostream :(
      • 问题要求中没有说明。
      【解决方案5】:

      您可以operator[] 并使其返回指向矩阵的相应row or column 的指针。 因为指针支持 [ ] 下标,所以可以通过'double-square'notation [][] 访问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-19
        • 1970-01-01
        • 2016-04-08
        • 2012-06-02
        • 2014-01-14
        • 2013-12-03
        • 2013-06-07
        相关资源
        最近更新 更多