arraysoperator-overloadingdarrayiterator

iterating over an array of custom objects in D


I am having an issue creating some way to iterate or even access elements in an array of custom objects in D.

I have created the array by:

class Database{

public:
    this(){ /* STUBB */}

    void addRow(DataRow input){ this.db ~= input; }

private:
    static uint count;
    DataRow[] db;
}

but when i try and access the individual elements in the array by:

string x = db[1].getCountryName();

I get an error:

Error: no [] operator overload for type Database.Database

It has been a really long time since I've done any coding in C/ C++, and this is my first attempt at D. I'm not exactly sure what to do. how would i go about overloading the [] operator?


Solution

  • By overloading the index operator.

    http://dlang.org/operatoroverloading.html#array

    For example:

    struct A
    {
        int opIndex(size_t i1, size_t i2, size_t i3);
    }
    
    void test()
    {
        A a;
        int i;
        i = a[5,6,7];  // same as i = a.opIndex(5,6,7);
    }