简体   繁体   中英

How do I implement operator[] for dynamic array?

I need to implement a dynamic array by myself to use it in a simple memory manager.

struct Block {       
    int* offset;
    bool used;
    int size;
    Block(int* off=NULL, bool isUsed=false, int sz=0): offset(off), used(isUsed), size(sz) {}
    Block(const Block& b): offset(b.offset), used(b.used), size(b.size) {}
};

class BlockList {
    Block* first;
    int size;
public:
    BlockList(): first(NULL), size(0) {}
    void PushBack(const Block&);
    void DeleteBack();
    void PushMiddle(int, const Block&);
    void DeleteMiddle(int);
    int Size() const { return size; }
    void show();
    Block& operator[](int);
    Block* GetElem(int);
    void SetElem(int, const Block&);
    ~BlockList();
};

I need to overload operator[] .

Block& BlockList::operator\[\](int index) {
    try {
        if (index >= size)
            throw out_of_range("index out of range");
        else 
            return (first[sizeof(Block)*index]);
    }
    catch(exception& e) {
        cerr << e.what() << endl;
    }
}

void BlockList::PushBack(const Block& b) {
    if(!size) 
        first = new Block(b);
    else {
        Block* temp = new Block[size + 1];
        int i = 0;
        for (i = 0; i < size; i++) 
            temp[sizeof(Block)*i] = this->operator[](i);
        delete []first;
        temp += sizeof(Block);
        temp->offset = b.offset;
        temp->size = b.size;
        temp->used = b.used;
        first = temp;
    }
    size++;
}

When I use PushBack to push the first element, it works OK, but when it comes to the second, third, ..., the program didn't crash, but it just shows results I didn`t expect to see.

Here is how I get the contents of my array:

void BlockList::show() {
    for (int i = 0; i < size; i++) {
        Block current(operator[](i));
        cout << "off: " << current.offset << " size: " << current.size << endl;
    }
}

first is a Block pointer so you only need to pass in index .

Block* first; ...

first[0] //returns the first element
first[1] //returns the second element

In your example you are passing in too high of an index value when indexing first because you're using sizeof inside.

Corrected code:

Block& BlockList::operator[](int index) {
    try {
        if (index >= size)
            throw out_of_range("index out of range");
        else 
            return (first[index]);//<--- fix was here
    }
    catch(exception& e) {
        cerr << e.what() << endl;
    }
}

An array knows how big its elements are, so you don't have to do the math with sizeof(Block) . Just use i as the index.

On a related note, the C++ FAQ Lite has a great section on operator overloading that covers all kinds of useful stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM