我创建了一个名为ring的类,它的工作原理如下:
ring<std::string> example(2);
examples.add("one");
examples.add("two");
examples.add("three"); // this element will replace the first element
另外,我尝试使其变得可迭代,但由于异常访问冲突读取位置而崩溃,该异常位置位于主for循环中的cout处,而该程序在没有for循环的情况下运行良好
铃声类:
template <class input>
class ring {
public:
class iterator;
private:
input* data;
int size;
int pos = 0;
public:
ring(const int size) : size(size), data(NULL) { data = new input[size]; }
~ring() { delete[] data; }
void add(input in) {
if (pos == size)
pos = 0;
data[pos++] = in;
}
iterator begin() { return iterator(0, *this); }
iterator end() { return iterator(size - 1, *this); }
input& get(int i) { return data[i]; }
};
迭代器类:
template <class input>
class ring<input>::iterator {
private:
int m_pos;
ring m_ring;
public:
iterator(int pos, ring& aRing) : m_pos(pos), m_ring(aRing) {}
~iterator() {}
input& operator* () { return m_ring.get(m_pos); }
bool operator!= (const iterator& other) const { return m_pos != other.m_pos; }
iterator& operator++(int) {
m_pos++;
return *this;
}
iterator& operator++() {
m_pos++;
return *this;
}
};
主要:
int main() {
ring<string> textring(3);
textring.add("one");
textring.add("two");
textring.add("three");
textring.add("four");
for (auto text : textring) {
cout << text << endl;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句