我正在使用“动态内存分配”来为作业分配一个数组,不允许我们使用默认的C ++数组或向量。
在调整大小的方法中,我创建了一个具有所需大小的新数组,复制了旧数组的数据,然后尝试删除coeffPtr,然后重新分配它。
Visual Studio在删除行上引发异常,但无法告诉我该异常是什么。
此代码有什么问题?
编辑:我已经对其进行了更新,以包括最小的.h,.cpp和驱动程序以说明问题。另外要澄清的是,我目前在CSS343(本质上是C ++的第2部分)中有一个糟糕的342教师(第1部分),所以不,我不记得曾经教过的3规则。也就是说,我很快实现了析构函数,提供了赋值重载器,即使它没有被使用。
poly.h
#ifndef POLYSMALL_H
#define POLYSMALL_H
class Poly {
public:
// Constructor
Poly(int coefficient, int exponent);
// Destructor
~Poly();
// Setter
void setCoeff(int, int);
// Array Functions
void resize(int);
void copy(const Poly&);
// Assignment operators
const Poly &operator=(const Poly&);
private:
// Allocated Memory
int* coeffPtr = nullptr;
int size;
};
#endif // POLYSMALL_H
poly.cpp
#include "polysmall.h"
// Constructor with two inputs
Poly::Poly(int coefficient, int exponent) {
// Initialize the polynomial array with the length of the exponent
// +1 because arrays starting at 0 rather than one
coeffPtr = new int[exponent];
size = exponent;
for (int i = 0; i < size; i++) {
coeffPtr[i] = 0;
}
coeffPtr[exponent] = coefficient;
}
// Destructor
Poly::~Poly() {
delete[] coeffPtr;
}
// Setter
void Poly::setCoeff(int coefficient, int exponent) {
// Check to see if exponent is greater than array index
if (exponent > size) {
resize(exponent);
}
coeffPtr[exponent] = coefficient;
}
// Resize
void Poly::resize(int newSize) {
// Create new array
int* newCoeffPtr = new int[newSize];
// Create int values for the array
for (int i = 0; i < newSize; i++) {
newCoeffPtr[i] = 0;
}
// Copy over data
for (int i = 0; i < size && i < newSize; i++) {
newCoeffPtr[i] = coeffPtr[i];
}
// Update size
size = newSize;
// Delete old array
delete[] coeffPtr;
// Assign new array
coeffPtr = newCoeffPtr;
}
void Poly::copy(const Poly& polynomial) {
// Adjust size of array if needed
if (size < polynomial.size) {
resize(polynomial.size);
}
// Copy over data
for (int i = 0; i < size; i++) {
coeffPtr[i] = polynomial.coeffPtr[i];
}
}
const Poly &Poly::operator=(const Poly &polynomial) {
// Resize our array to match new poly's array
if (polynomial.size != size) {
resize(polynomial.size);
}
// Copy over data
for (int i = 0; i < size; i++) {
coeffPtr[i] = polynomial.coeffPtr[i];
}
// Return this
return *this;
}
driver.cpp
#include "polysmall.h"
#include <iostream>
using namespace std;
int main() {
// Create polynomial of 2x^4 or of an array of [0,0,0,2]
Poly polynomial(2,4);
// Attempt to set index of 5 to 3
// Invokes resize to adjust array to [0,0,0,2,0]
polynomial.setCoeff(3, 5);
return 0;
}