c ++中数组的构造函数初始化列表

时间:2017-12-13 11:48:48

标签: c++ arrays constructor

我在下面的课程中创建了学生成绩记录。构造函数为数组分配内存,并为数组中的每个元素设置默认值。我必须传入这个默认值的值。我的问题是,我可以分配内存并使用构造初始化列表或以任何其他方式初始化数组的值。我不知道如何使用动态分配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 个答案:

答案 0 :(得分: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中进行适当的更改。