1

我需要自己实现一个动态数组才能在简单的内存管理器中使用它。

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();
};

我需要超载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++;
}

当我使用PushBackpush第一个元素时,它工作正常,但是当涉及到第二个,第三个,......时,程序并没有崩溃,而是显示了我没想到的结果。

这是我获取数组内容的方法:

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

2 回答 2

3

first是一个Block指针,所以你只需要传入index

首先阻止*;...

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

在您的示例中,您在第一次建立索引时传递了太高的索引值,因为您在内部使用了 sizeof。

更正的代码:

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;
    }
}
于 2009-02-28T13:50:14.643 回答
1

数组知道它的元素有多大,所以你不必用sizeof(Block). 只需i用作索引。

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

于 2009-02-28T13:52:45.527 回答