【发布时间】:2017-12-13 11:48:47
【问题描述】:
我在下面有一个创建学生成绩记录的课程。构造函数为数组分配内存并为数组中的每个元素设置一个默认值。我必须传入这个默认值的值。我的问题是,我可以使用构造初始化列表或任何其他方式分配内存并初始化数组的值吗?我不使用动态分配new 和delete。
//header file for main.cpp
#include<iostream>
using namespace std;
const int SIZE = 5;
template <class T>
class StudentRecord
{
private:
const int size = SIZE;
T grades[SIZE];
int studentId;
public:
StudentRecord(T defaultInput);//A default constructor with a default value
void setGrades(T* input);
void setId(int idIn);
void printGrades();
};
template<class T>
StudentRecord<T>::StudentRecord(T defaultInput)
{
//we use the default value to allocate the size of the memory
//the array will use
for(int i=0; i<SIZE; ++i)
grades[i] = defaultInput;
}
template<class T>
void StudentRecord<T>::setGrades(T* input)
{
for(int i=0; i<SIZE;++i)
{
grades[i] = input[i];
}
}
template<class T>
void StudentRecord<T>::setId(int idIn)
{
studentId = idIn;
}
template<class T>
void StudentRecord<T>::printGrades()
{
std::cout<<"ID# "<<studentId<<": ";
for(int i=0;i<SIZE;++i)
std::cout<<grades[i]<<"\n ";
std::cout<<"\n";
}
#include "main.hpp"
int main()
{
//StudentRecord is the generic class
StudentRecord<int> srInt();
srInt.setId(111111);
int arrayInt[SIZE]={4,3,2,1,4};
srInt.setGrades(arrayInt);
srInt.printGrades();
return 0;
}
【问题讨论】:
-
有什么理由不能使用 std::vector?
-
C++ 没有运行时可变长度数组,除非通过内存分配。因此,您的选择是使用分配或使用一个足够大的数组以实现 SIZE 的最大可能值并存储每个对象中使用的实际数字。
标签: c++ arrays constructor