2017-12-13 10 views
0

나는 아래의 클래스를 통해 학생 성적 레코드를 만듭니다. 생성자는 배열의 메모리를 할당하고 배열의 각 요소에 기본값을 설정합니다. 이 기본값의 값을 전달해야합니다. 내 질문은, 내가 메모리를 할당하고 초기화 목록을 구성하거나 다른 방법으로 배열의 값을 초기화 할 수 있습니다. 나는 동적 할당 newdelete을 사용하지 않을 것이다.배열에 대한 생성자 초기화 목록

//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; 
} 
+1

std :: vector를 사용할 수없는 이유는 무엇입니까? – UKMonkey

+0

C++에는 메모리 할당을 통하는 경우를 제외하고는 런타임 가변 길이 배열이 없습니다. 따라서 할당을 사용하거나 SIZE의 가능한 최대 값에 충분한 크기의 배열을 사용하고 각 객체에 사용 된 실제 숫자를 저장해야합니다. –

답변

1

예. 가능합니다. 다음은 그 예입니다. Here you can see it working :

class A 
{ 
     int valLen; 
     int* values; 
     vector<int> vect; 

    public: 
     A(int len, ...) 
     { 
      va_list args; 
      va_start(args, len); 
      valLen = len; 
      for(int i=0; i<valLen; i++) 
      { 
       vect.push_back(va_arg(args, int)); 
      } 
      values = &vect[0]; 
      va_end(args); 
     } 

     void print() 
     { 
      for(int i=0; i<valLen; i++) 
       cout << values[i]<<endl; 
     } 
}; 

int main() 
{ 
    A aVals[] ={A(3, 50,6,78), A(5, 67,-10,89,32,12)}; 

    for(int i=0; i<2; i++) 
    { 
     aVals[i].print(); 
     cout<<"\n\n"; 
    } 
    return 0; 
} 

참고 : 생성자 첫 인자 값의 수, 즉 count 수가 통과한다. count이 수정 된 경우 constructor을 건너 뛰고 해당 변경을 수행 할 수 있습니다.

+0

여기에 5 개의 객체 배열을 각각 고유 한 값으로 생성하지 않습니까? 나는 5 개의 값을 저장하는 배열 인 grades라는 변수를 가진 하나의 객체를 만드는 방법을 묻고있었습니다. 그래서 구조 초기화 목록을 사용하여 해당 배열의 값을 초기화 할 수 있습니다 궁금 해서요? –