我试图为我的类" IntList"实现一个拷贝构造函数,但是我一直收到内存泄漏错误并且很难识别它!
这是我的复制构造函数的实现!
IntList::IntList(const IntList& source) {
Node *y = source.first;
first = new Node;
Node *x = first;
while(y->next != nullptr){
x->info = y->info;
x -> next = new Node;
x = x->next;
y = y->next;
}
x->next = nullptr;
x->info = y->info;
}
这是Inklist Class!
class IntList {
public:
// ctor and 3 methods already done in intlist.cpp:
IntList(); // constructor
void append(int value); // append value at end of list
void print() const; // print values separate by ' '
int count() const; // return count of values
// dtor, copy ctor and 6 other METHODS YOU MUST
// IMPLEMENT IN intlist.cpp:
~IntList(); // destructor
IntList(const IntList& source); //copy constructor (deep copy)
int sum() const; // sum of all values
bool contains(int value) const; // true if value in list
int max() const; // maximum value
double average() const; // average of all values
void insertFirst(int value); // insert new first value
IntList& operator=(const IntList& source); //overloaded
private:
// definition of Node structure (DO NOT CHANGE):
struct Node {
int info;
Node *next;
};
Node *first; // pointer to first node
};
答案 0 :(得分:2)
您的析构函数需要遍历列表并delete
您new
所有节点