0

How to overload C++ operator [][] in class Matrix if want to return vector of vectors Data?

   class Matrix
{
public:
    Matrix(int rows, int columns);
   // double operator[][](int RowIndex,int ColIndex);

    class Proxy {
        public:
            Proxy(int pCol){
                pData.resize(pCol);
            }

            double& operator[](int index) {
                return pData[index];
            }
        private:
            std::vector<double> pData;
        };

        Proxy operator[](int index) {
            return Proxy(Data[index]);
        }

protected:
    int Rows;
    int Columns;
    std::vector<std::vector<double>> Data;


};

error: no matching function for call to ‘Matrix::Proxy::Proxy(__gnu_cxx::__alloc_traits > >::value_type&)’ return Proxy(Data[index]);

so i need smth like this:

    double& operator[][](int IndexRow,int IndexCol){
        return Data[IndexRow][IndexCol];
    }
icegas
  • 71
  • 1
  • 1
  • 9
  • 3
    There ain't no such thing as `operator[][]`. There's `operator[]`, which may return something to which `[]` in turn may apply. – Igor Tandetnik Jun 17 '17 at 12:53
  • 2
    A simple implementation could be `std::vector& operator[](std::size_t i) { return Data[i]; }`, which will do what you want -- though it will break encapsulation. You will have to use the proxy object approach in the linked duplicate if you don't want to expose the internal vector detail. – cdhowie Jun 17 '17 at 12:53
  • Welcome to Stack Overflow. Please take the time to read [The Tour](http://stackoverflow.com/tour) and refer to the material from the [Help Center](http://stackoverflow.com/help/asking) what and how you can ask here. – πάντα ῥεῖ Jun 17 '17 at 12:54
  • https://stackoverflow.com/questions/15762878/c-overload-operator this is helpful source. – icegas Jun 17 '17 at 14:11
  • define your [] operator as follows: `std::vector& operator[](size_t i) { return Data[i]; }` – Michaël Roy Jun 17 '17 at 23:58

0 Answers0