我正在用c ++进行赋值,其中我们必须重写从抽象Container类继承的std :: vector类。我们必须为'Vector'编写方法,例如begin(),end(),push_back()等。 许多基本的std :: vector成员函数可以在这里找到:http://www.cplusplus.com/reference/vector/vector/
我的问题是多方面的,主要是因为我是一个初学者,并且计算机的记忆令人着迷。另外,很抱歉,如果这个问题是超级特定的,或者在这里有类似的答案,但我真的很困惑,因为这是我第一次处理记忆。
这是我的Container和Vector类的实现:
template <typename T>
class Container {
protected:
T* elem;
int cap;
public:
virtual T& operator[](int i) = 0;
virtual int size() = 0;
~ Container() { delete[] elem; }
};
template <typename T>
class Vector: public Container<T> {
protected:
using Container<T>::elem;
using Container<T>::cap;
private:
int sz;
public:
// constructors
Vector(); // default constructor
Vector(int n); // fill constructor #1
Vector(int n, T fill_val); // fill constructor #2
/* // ~ Vector(); // destructors
unsure if the above is correct, because of the Container destructor
*/
// overloaded operators
T& operator[](int i); // subscript overloading '[]'
T& operator=(const Vector<T>& V); // assignment overloading '='
// access methods
T& front(); //returns a reference to the first element
T& back(); //returns a reference to the last element
// iterator methods
T* begin(); // returns memory address of the first element
T* end(); // returns memory address at the end
// size methods
int size() { return sz; }
int capacity() { return cap; }
};
第2部分。
何时/为什么需要析构函数?我试图阅读Stack上的析构函数,但我感到比澄清更困惑。我假设SegFault来自需要释放的内存,并且我知道我应该学习如何通过此分配动态分配内存。构造函数和析构函数对于此过程至关重要,但是有人可以对我尽可能简单地分解它吗?
编辑:
我通过实施Fureeish的答案解决了细分错误。我的代码已在上面更新。
唯一剩下的询问是对销毁者及其目的的询问。我需要为Vector
实现一个还是由Container
自动调用?
答案 0 :(得分:1)
您决定自己管理内存,但从未分配任何内存。您到处都缺少一些new
。例如,给定一个:
Vector(int n, T fill_val) {
sz = n;
cap = 2*n;
for(int i = 0; i < sz; i++) {
elem[i] = fill_val;
}
}
for()
循环遍历elem
,后者是未初始化的指针。您将其视为指向动态分配数组的指针,但是它只是指向一些垃圾值。记住-首先分配,然后进行处理(仅当您决定自己管理内存时才 。通常,您应该更喜欢使用标准实现)。
正确的版本应如下所示:
Vector(int n, T fill_val) {
sz = n;
cap = 2*n;
elem = new T[cap]; // or cap-1, depending on what you do with `end()`.
for(int i = 0; i < sz; i++) {
elem[i] = fill_val;
}
}
您在使用其他构造函数时从未遇到此问题的事实是,您非常幸运,未定义行为是偷偷摸摸的