【问题标题】:How do I implement operator[] for dynamic array?如何为动态数组实现 operator[]?
【发布时间】:2009-02-28 13:44:30
【问题描述】:

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

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++;
}

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

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

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

【问题讨论】:

  • 为什么不使用 std::vector?如果您希望它与您的内存管理器一起使用,请将其传递给自定义分配器。您似乎解决了错误的问题。
  • 因为这项工作的目的是让编译器能够自行编译,所以我可以t use STL and templates - its 太难从头实现模板

标签: c++ arrays dynamic-data


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    数组知道它的元素有多大,因此您不必使用sizeof(Block) 进行数学运算。只需使用i 作为索引即可。

    在相关说明中,C++ FAQ Lite 有一个关于运算符重载的精彩部分,涵盖了各种有用的内容。

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 2021-04-14
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      相关资源
      最近更新 更多