I'm making a class called DblArray, and doing basic functions for it. I seem to be getting a problem when compiling, though, as it says "incorrect checksum for freed object - object was probably modified after being freed." I'll post all of my code below, but I think the problem is happening in this function:
void DblArray::insertVal(double n)
{
if ( size == capacity )
{
capacity *= 2;
double temp[size];
for ( int i = 0; i < size; i++ )
temp[i] = data[i];
delete [] data;
data = 0;
data = new double[capacity];
for ( int i = 0; i < size; i++ )
data[i] = temp[i];
}
size++;
data[size] = n;
}
The header file is this:
#include <iostream>
#ifndef DBLARRAY_H
#define DBLARRAY_H
class DblArray
{
private:
long capacity;
long size;
double * data;
public:
DblArray();
~DblArray();
DblArray(const DblArray& d);
DblArray& operator = (const DblArray& d);
double operator [] (int i);
long getCapacity();
long getSize();
double getAverage();
void insertVal(double);
void removeVal();
};
#endif // DBLARRAY_H
The implementation file is this:
#include "DblArray.h"
DblArray::DblArray()
{
capacity = 1;
size = 0;
data = new double[capacity];
}
DblArray::~DblArray()
{
capacity = 0;
size = 0;
delete [] data;
data = NULL;
}
DblArray::DblArray(const DblArray& d)
{
capacity = d.capacity;
size = d.size;
data = new double[capacity];
for ( int i = 0; i < size; i++ )
{
data[i] = d.data[i];
}
}
DblArray& DblArray::operator = (const DblArray& d)
{
DblArray dNew;
dNew.capacity = d.capacity;
dNew.size = d.size;
dNew.data = new double[capacity];
for ( int i = 0; i < dNew.size; i++ )
{
dNew.data[i] = d.data[i];
}
return dNew;
}
double DblArray::operator [] (int i)
{
return data[i];
}
long DblArray::getCapacity()
{
return capacity;
}
long DblArray::getSize()
{
return size;
}
double DblArray::getAverage()
{
double average = 0;
for ( int i = 0; i < size; i++ )
{
average += data[i];
}
average = average / size;
return average;
}
void DblArray::insertVal(double n)
{
if ( size == capacity )
{
capacity *= 2;
double temp[size];
for ( int i = 0; i < size; i++ )
temp[i] = data[i];
delete [] data;
data = 0;
data = new double[capacity];
for ( int i = 0; i < size; i++ )
data[i] = temp[i];
}
size++;
data[size] = n;
}
void DblArray::removeVal()
{
data[size] = 0;
}
And the driver is this:
#include <iostream>
#include "DblArray.h"
using namespace std;
DblArray print( DblArray );
int main()
{
//Data abstractions
DblArray d1;
//Printing the contents of d1 before testing functions
print(d1);
for ( int i = 0; i < 5; i++ )
{
d1.insertVal(i);
}
//Printing contents of d1 after adding values
print(d1);
return 0;
}
//Function to print the contents of each object
DblArray print( DblArray d )
{
cout << "Capacity:\t" << d.getCapacity() << endl;
cout << "Size:\t" << d.getSize() << endl;
cout << "Data:\t" << endl;
for ( int i = 0; i < d.getSize(); i++ )
{
cout << d[i] << "\t";
}
cout << "\n";
}
Aucun commentaire:
Enregistrer un commentaire