簡體   English   中英

運算符[][] 重載

[英]Operator[][] overload

是否可以重載[]運算符兩次? 為了允許,像這樣: function[3][3] (就像在二維數組中一樣)。

如果可能的話,我想看看一些示例代碼。

您可以重載operator[]以返回一個對象,您可以在該對象上再次使用operator[]來獲得結果。

class ArrayOfArrays {
public:
    ArrayOfArrays() {
        _arrayofarrays = new int*[10];
        for(int i = 0; i < 10; ++i)
            _arrayofarrays[i] = new int[10];
    }

    class Proxy {
    public:
        Proxy(int* _array) : _array(_array) { }

        int operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };

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

private:
    int** _arrayofarrays;
};

然后你可以像這樣使用它:

ArrayOfArrays aoa;
aoa[3][5];

這只是一個簡單的例子,你想添加一堆邊界檢查和東西,但你明白了。

具體而言,對於二維數組,您可能會使用單個 operator[] 重載,該重載返回指向每行第一個元素的指針。

然后您可以使用內置索引運算符來訪問行中的每個元素。

表達式x[y][z]要求x[y]計算為支持d[z]的對象d

這意味着x[y]應該是一個帶有operator[]的對象,該對象的計算結果為支持operator[]的“代理對象”。

這是鏈接它們的唯一方法。

或者,重載operator()以接受多個參數,這樣您就可以調用myObject(x,y)

如果您在第一個 [] 調用中返回某種代理類,則有可能。 但是,還有其他選擇:您可以重載可以接受任意數量參數( function(3,3) )的 operator() 。

一種方法是使用std::pair<int,int>

class Array2D
{
    int** m_p2dArray;
public:
    int operator[](const std::pair<int,int>& Index)
    {
       return m_p2dArray[Index.first][Index.second];
    }
};

int main()
{
    Array2D theArray;
    pair<int, int> theIndex(2,3);
    int nValue;
    nValue = theArray[theIndex];
}

當然,你可以typedef pair<int,int>

您可以使用代理對象,如下所示:

#include <iostream>

struct Object
{
    struct Proxy
    {
        Object *mObj;
        int mI;

        Proxy(Object *obj, int i)
        : mObj(obj), mI(i)
        {
        }

        int operator[](int j)
        {
            return mI * j;
        }
    };

    Proxy operator[](int i)
    {
        return Proxy(this, i);
    }
};

int main()
{
    Object o;
    std::cout << o[2][3] << std::endl;
}

如果您能告訴我functionfunction[x]function[x][y]是什么,那就太好了。 但無論如何讓我將其視為在某處聲明的對象

SomeClass function;

(因為你說它是運算符重載,我想你不會對像SomeClass function[16][32];這樣的數組感興趣)

所以functionSomeClass類型的一個實例。 然后查找SomeClass聲明以獲取operator[]重載的返回類型,就像

ReturnType operator[](ParamType);

然后function[x]將具有ReturnType類型。 再次查找operator[]重載的ReturnType 如果有這樣的方法,那么您可以使用表達式function[x][y]

請注意,與function(x, y)function[x][y]是 2 個單獨的調用。 因此,除非您在上下文中使用鎖,否則編譯器或運行時很難保證原子性。 一個類似的例子是,libc 說printf是原子的,而連續調用輸出流中的重載operator<<不是。 像這樣的聲明

std::cout << "hello" << std::endl;

在多線程應用程序中可能有問題,但類似

printf("%s%s", "hello", "\n");

很好。

如果你不想說 a[x][y],而是想說 a[{x,y}],你可以這樣做:

struct Coordinate {  int x, y; }

class Matrix {
    int** data;
    operator[](Coordinate c) {
        return data[c.y][c.x];
    }
}
#include<iostream>

using namespace std;

class Array 
{
     private: int *p;
     public:
          int length;
          Array(int size = 0): length(size)
          {
                p=new int(length);
          }
          int& operator [](const int k)
          {
               return p[k];
          }
};
class Matrix
{
      private: Array *p;
      public: 
            int r,c;
            Matrix(int i=0, int j=0):r(i), c(j)
            {
                 p= new Array[r];
            }
            Array& operator [](const int& i)
            {
                 return p[i];
            }
};

/*Driver program*/
int main()
{
    Matrix M1(3,3); /*for checking purpose*/
    M1[2][2]=5;
}
struct test
{
    using array_reference = int(&)[32][32];

    array_reference operator [] (std::size_t index)
    {
        return m_data[index];
    }

private:

    int m_data[32][32][32];
};

找到了我自己的簡單解決方案。

template<class F>
struct indexer_t{
  F f;
  template<class I>
  std::result_of_t<F const&(I)> operator[](I&&i)const{
    return f(std::forward<I>(i))1;
  }
};
template<class F>
indexer_t<std::decay_t<F>> as_indexer(F&& f){return {std::forward<F>(f)};}

這使您可以使用 lambda,並生成一個索引器(具有[]支持)。

假設您有一個operator()支持將 onxe 的兩個坐標作為兩個參數傳遞。 現在編寫[][]支持只是:

auto operator[](size_t i){
  return as_indexer(
    [i,this](size_t j)->decltype(auto)
    {return (*this)(i,j);}
  );
}

auto operator[](size_t i)const{
  return as_indexer(
    [i,this](size_t j)->decltype(auto)
    {return (*this)(i,j);}
  );
}

並做了。 不需要自定義類。

可以使用專門的模板處理程序重載多個 []。 只是為了展示它是如何工作的:

#include <iostream>
#include <algorithm>
#include <numeric>
#include <tuple>
#include <array>

using namespace std;

// the number '3' is the number of [] to overload (fixed at compile time)
struct TestClass : public SubscriptHandler<TestClass,int,int,3> {

    // the arguments will be packed in reverse order into a std::array of size 3
    // and the last [] will forward them to callSubscript()
    int callSubscript(array<int,3>& v) {
        return accumulate(v.begin(),v.end(),0);
    }

};

int main() {


    TestClass a;
    cout<<a[3][2][9];  // prints 14 (3+2+9)

    return 0;
}

現在定義SubscriptHandler<ClassType,ArgType,RetType,N>使之前的代碼工作。 它只顯示了如何做到這一點。 此解決方案是最佳的,也沒有錯誤(例如,不是線程安全的)。

#include <iostream>
#include <algorithm>
#include <numeric>
#include <tuple>
#include <array>

using namespace std;

template <typename ClassType,typename ArgType,typename RetType, int N> class SubscriptHandler;

template<typename ClassType,typename ArgType,typename RetType, int N,int Recursion> class SubscriptHandler_ {

    ClassType*obj;
    array<ArgType,N+1> *arr;

    typedef SubscriptHandler_<ClassType,ArgType,RetType,N,Recursion-1> Subtype;

    friend class SubscriptHandler_<ClassType,ArgType,RetType,N,Recursion+1>;
    friend class SubscriptHandler<ClassType,ArgType,RetType,N+1>;

public:

    Subtype operator[](const ArgType& arg){
        Subtype s;
        s.obj = obj;
        s.arr = arr;
        arr->at(Recursion)=arg;
        return s;
    }
};

template<typename ClassType,typename ArgType,typename RetType,int N> class SubscriptHandler_<ClassType,ArgType,RetType,N,0> {

    ClassType*obj;
    array<ArgType,N+1> *arr;

    friend class SubscriptHandler_<ClassType,ArgType,RetType,N,1>;
    friend class SubscriptHandler<ClassType,ArgType,RetType,N+1>;

public:

    RetType operator[](const ArgType& arg){
        arr->at(0) = arg;
        return obj->callSubscript(*arr);
    }

};


template<typename ClassType,typename ArgType,typename RetType, int N> class SubscriptHandler{

    array<ArgType,N> arr;
    ClassType*ptr;
    typedef SubscriptHandler_<ClassType,ArgType,RetType,N-1,N-2> Subtype;

protected:

    SubscriptHandler() {
        ptr=(ClassType*)this;
    }

public:

    Subtype operator[](const ArgType& arg){
        Subtype s;
        s.arr=&arr;
        s.obj=ptr;
        s.arr->at(N-1)=arg;
        return s;
    }
};

template<typename ClassType,typename ArgType,typename RetType> struct SubscriptHandler<ClassType,ArgType,RetType,1>{
    RetType operator[](const ArgType&arg) {
        array<ArgType,1> arr;
        arr.at(0)=arg;
        return ((ClassType*)this)->callSubscript(arr);
    }
};

vector< vector< T > > 或 T** 僅當您有可變長度的行並且在內存使用/分配方面效率太低時才需要,如果您需要矩形數組,請考慮做一些數學運算! 參見 at() 方法:

template<typename T > class array2d {

protected:
    std::vector< T > _dataStore;
    size_t _sx;

public:
    array2d(size_t sx, size_t sy = 1): _sx(sx), _dataStore(sx*sy) {}
    T& at( size_t x, size_t y ) { return _dataStore[ x+y*sx]; }
    const T& at( size_t x, size_t y ) const { return _dataStore[ x+y*sx]; }
    const T& get( size_t x, size_t y ) const { return at(x,y); }
    void set( size_t x, size_t y, const T& newValue ) { at(x,y) = newValue; }
};

使用std::vector<std::vector<type*>> ,您可以使用自定義輸入運算符構建內部向量,該運算符迭代您的數據並返回指向每個數據的指針。

例如:

size_t w, h;
int* myData = retrieveData(&w, &h);

std::vector<std::vector<int*> > data;
data.reserve(w);

template<typename T>
struct myIterator : public std::iterator<std::input_iterator_tag, T*>
{
    myIterator(T* data) :
      _data(data)
    {}
    T* _data;

    bool operator==(const myIterator& rhs){return rhs.data == data;}
    bool operator!=(const myIterator& rhs){return rhs.data != data;}
    T* operator*(){return data;}
    T* operator->(){return data;}

    myIterator& operator++(){data = &data[1]; return *this; }
};

for (size_t i = 0; i < w; ++i)
{
    data.push_back(std::vector<int*>(myIterator<int>(&myData[i * h]),
        myIterator<int>(&myData[(i + 1) * h])));
}

活生生的例子

此解決方案的優點是為您提供了一個真正的 STL 容器,因此您可以使用特殊的 for 循環、STL 算法等。

for (size_t i = 0; i < w; ++i)
  for (size_t j = 0; j < h; ++j)
    std::cout << *data[i][j] << std::endl;

但是,它確實創建了指針向量,因此如果您使用像這樣的小型數據結構,您可以直接復制數組內的內容。

示例代碼:

template<class T>
class Array2D
{
public:
    Array2D(int a, int b)  
    {
        num1 = (T**)new int [a*sizeof(int*)];
        for(int i = 0; i < a; i++)
            num1[i] = new int [b*sizeof(int)];

        for (int i = 0; i < a; i++) {
            for (int j = 0; j < b; j++) {
                num1[i][j] = i*j;
            }
        }
    }
    class Array1D
    {
    public:
        Array1D(int* a):temp(a) {}
        T& operator[](int a)
        {
            return temp[a];
        }
        T* temp;
    };

    T** num1;
    Array1D operator[] (int a)
    {
        return Array1D(num1[a]);
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    Array2D<int> arr(20, 30);

    std::cout << arr[2][3];
    getchar();
    return 0;
}

使用 C++11 和標准庫,您可以在一行代碼中創建一個非常好的二維數組:

std::array<std::array<int, columnCount>, rowCount> myMatrix {0};

std::array<std::array<std::string, columnCount>, rowCount> myStringMatrix;

std::array<std::array<Widget, columnCount>, rowCount> myWidgetMatrix;

通過決定內部矩陣代表行,您可以使用myMatrix[y][x]語法訪問矩陣:

myMatrix[0][0] = 1;
myMatrix[0][3] = 2;
myMatrix[3][4] = 3;

std::cout << myMatrix[3][4]; // outputs 3

myStringMatrix[2][4] = "foo";
myWidgetMatrix[1][5].doTheStuff();

您還可以使用ranged- for輸出:

for (const auto &row : myMatrix) {
  for (const auto &elem : row) {
    std::cout << elem << " ";
  }
  std::cout << std::endl;
}

(決定內部array代表列將允許使用foo[x][y]語法,但您需要使用笨拙的for(;;)循環來顯示輸出。)

我的5美分。

我憑直覺知道我需要做很多樣板代碼。

這就是為什么我沒有重載運算符[],而是重載了運算符(int,int)。 然后在最終結果中,我做了m(1,2),而不是m [1] [2]

我知道這是不同的事情,但仍然非常直觀,看起來像數學腳本。

最短和最簡單的解決方案:

class Matrix
{
public:
  float m_matrix[4][4];

// for statements like matrix[0][0] = 1;
  float* operator [] (int index) 
  {
    return m_matrix[index];
  }

// for statements like matrix[0][0] = otherMatrix[0][0];
  const float* operator [] (int index) const 
  {
    return m_matrix[index];
  }

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM