【发布时间】:2014-10-03 13:58:31
【问题描述】:
我正在尝试实现一个 GradeManager 类,该类在内部使用使用 new 运算符动态创建的 DataVector 对象数组来记录一组学生的作业成绩。
我正在努力制作构造函数/析构函数。
构造函数的说明:“这是班级的唯一构造函数,它指定班级的学生nStudents和作业nHW的数量。您应该使用它们来动态设置数组大小。”
您提供的任何想法都会有很大帮助!这就是我到目前为止所拥有的。非常感谢!!!
#include <iostream>
#include <cmath>
#include <iomanip>
//DO NOT INCLUDE ANYTHING ELSE!!
using namespace std;
typedef double DataType;//Alias for double type
typedef unsigned int UIntType;//Alias for unsigned int type
class DataVector
{
private:
DataType *m_data; //Pointer to dynamically allocated memory that holds all items
UIntType m_size; //Size of the m_data array
public:
DataVector()
{
m_data = new DataType[10];
for(int i = 0; i < 10; i++){
m_data[i]=0;
}
m_size = 10;
}
DataVector(UIntType initSize, DataType initValue)
{
int arraySize = initSize;
m_data = new DataType[arraySize];
for(int i = 0; i < arraySize; i++){
m_data[i] = initValue;
}
m_size = initSize;
}
~DataVector()
{
delete [] m_data;
m_data = NULL;
}
UIntType GetSize()
{
return m_size;
}
void Reserve(UIntType newSize)
{
int arraySize = newSize;
DataType *new_data;
new_data = new DataType[arraySize];
for(int i = 0; i < m_size; i++){
new_data[i] = m_data[i];}
m_data = new_data;
m_size = newSize;
}
};
class GradeManager
{
private:
DataVector *m_student;//m_student[0], m_student[1], etc correspond to sID 0, 1, etc respectively
UIntType m_nStudents;//Number of students
public:
GradeManager(UIntType nStudents, UIntType nHWs)
{
m_student = new DataVector[nStudents];
m_student->Reserve(nHWs);
m_nStudents = nStudents;
}
~GradeManager()
{
int numOfStudents = m_nStudents;
for(int i = 0; i < numOfStudents; i++)
delete [] m_student;
m_student = NULL;
}
};
【问题讨论】:
-
第一个想法:使用
std::vector<> -
尽可能避免使用
new(仅在确实需要时使用),因为@quantdev 建议使用std::vector。 -
因此您不能包含任何其他内容,但您使用
NULL,不能保证在任何现有标题中。 -
评论
//DO NOT INCLUDE ANYTHING ELSE!!是否意味着这是家庭作业,您现在可以使用标准容器?
标签: c++ class dynamic-memory-allocation