我正在尝试在我的 List 类中创建一个动态数组,该数组的大小从 2 开始,当您使用 Insert 方法插入值时,它将检查是否有足够的空间,如果没有,它将调整数组的大小a size + 2 ... 问题是它正在崩溃 VS 抱怨堆损坏。另外我认为我的复制构造函数没有被调用,因为 cout 没有显示:
list.h 文件:
class List
{
public:
// DEFAULT Constructor
List();
// Deconstructor to free memory allocated
~List();// Prevent memory leaks
// COPY Constructor for pointers
List(const List& value);// copy constructor
//Modification methods
void Insert(const int);
// User ACCESS methods
void display(void) const;
private:
int size;// MAX size of the array
int count;// current number of elements in the dynamic array
protected:
int *intptr;// Our int pointer
};
list.cpp 实现文件:
#include "list.h" // Include our Class defintion
#include <iostream>
using namespace std;
// CONSTRUCTOR
List::List() {
size = 2; // initial size of array
count = 0;
intptr = new int[size]; // Start off 2 integers sized array
}
// DECONSTRUCTOR
List::~List() {
delete[] intptr; // free allocated memory
}
// Copy constructor
List::List(const List& value) {
size = value.size;
cout << "Copy con size : " << size << endl;
count = value.count;
cout << "Compy count : " << count << endl;
if (count < size) {
intptr = new int[size]; // Allocate new data
} else {
intptr = new int[size + 2]; // Allocate new data
}
for (int index = 0; index < count; index++) {
intptr[index] = value.intptr[index];
}
size = size + 2;
delete[] intptr;
intptr = value.intptr;
}
void List::Insert(const int value) {
// do we have room?
if (count < size) {
intptr[count] = value;
} else { // if not we need to add more elements to array
intptr[count] = value; // DEEP copy invoked with copy constructor
}
cout << "SIZE: " << size << endl;
cout << "COUNT" << count << endl;
count++; // Increase items added in array
}
void List::display() const {
for (int i = 0; i < count; i++)
cout << intptr[i] << endl;
}
main.cpp 测试器
#include <iostream>
#include "list.h"
int main()
{
List mylist;
mylist.Insert(5);
mylist.Insert(6);
mylist.Insert(2);
mylist.Insert(8);
mylist.Insert(4);
mylist.Insert(5);
mylist.Insert(9);
mylist.Insert(8);
mylist.Insert(5);
mylist.Insert(9);
mylist.Insert(8);
mylist.Insert(5);
mylist.Insert(9);
mylist.Insert(8);
mylist.Insert(5);
mylist.Insert(9);
mylist.display();
system("PAUSE");
return 0;
}