簡體   English   中英

C++如何定義操作符[]來寫入和讀取循環緩沖區的一項

[英]C++ how to define the operator [] to write and read an item of the circular buffer

我創建了一個實現循環緩沖區的模板類。 緩沖區由具有類型 T 值的項目組成。

我想定義 operator[] 來寫入和讀取緩沖區的元素。 即使我嘗試讀取已經初始化的元素,結果也是:分段錯誤:11

這是操作符[]的代碼:

// read
const T& operator[](size_type index) const {
    assert(index < _size);
    item *curr = _buffer + index;
    return curr->value;
  }
  
  // read and write
  T &operator[](size_type index) {
    assert(index < _capacity);

    item *curr = _buffer + index;

    if (index < _size) {
      return curr->value;
    }
    else {
      _size++;
      return curr->value;
    }
  }

我如何在 main.cpp 中使用 operator[] 的示例:

cbuffer<int> b(4);

  std::cout << "b: " << b << std::endl;
  std::cout << "capacity: " << b.capacity() << std::endl;
  assert(b.capacity() == 4);
  std::cout << "size: " << b.size() <<
                 std::endl;
  assert(b.size() == 0);

  b[0] = 1;
  b[1] = 3;

當我嘗試在緩沖區中寫入新項目時發生錯誤。

有什么方法可以定義有效的運算符 []?

我有點猜測,因為您沒有提供足夠的上下文(很難在沒有看到課程其余部分的情況下查看課程的一小部分是否正確)。 但似乎_buffer是一個鏈表。 項目結構中的next指針給出了它

typedef struct item {
    T value;
    item *next;
};

但是您的operator[]代碼假定_buffer是一個數組,

item *curr = _buffer + index;

在指針上使用+假定指針指向一個連續的內存塊,但因為您有一個鏈表,這對您來說並非如此。

相反,您需要編寫一個循環,循環遍歷您的鏈表,直到找到正確的項目。 像這樣的東西

item *curr = _buffer;
while (index > 0) {
    curr = curr->next;
    --index;
}
return curr->value;

暫無
暫無

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

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