私は生徒の成績記録を作成する以下のクラスを用意しました。コンストラクタは配列のメモリを割り当て、配列の各要素にデフォルト値を設定します。私はこのデフォルト値の値を渡す必要があります。私の質問は、メモリを割り当て、配列の値を初期化リストの構造体で初期化することができます。私は動的割り当てnew
とdelete
を使うべきではありません。配列のコンストラクタの初期化リストをC++で配列
//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を使用できない理由は何ですか? – UKMonkey
C++にはメモリ割り当て以外の実行時可変長配列はありません。したがって、割り当てを使用するか、SIZEの可能な最大値に十分な大きさの配列を使用し、各オブジェクトで使用されている実際の数を格納することです。 –