2

astd::arrayを使用すると、次のように初期化できます。

std::array<int,5> myArray = {1,2,3,4,5};

独自の配列クラスを作成しようとしている場合、どうすれば同様のことができますか?

4

2 に答える 2

1

要素のリストによる初期化をサポートする簡単な実装を次に示します。

//template class 'array' takes 'T' (the type of the array) and 'size'
template<typename T, std::size_t size>
class array
{
public:
    //This is the concept of initializer lists (wrapper around variadic arguments, that
    //allows for easy access)
    array(std::initializer_list<T> list)
    {
        //Loop through each value in 'list', and assign it to internal array
        for (std::size_t i = 0; i < list.size(); ++i)
            arr[i] = *(list.begin() + i); //list.begin() returns an iterator to the firsts
                                          //element, which can be moved using +
                                          //(deferenced to get the value)
    }

    //Overloads operator[] for easy access (no bounds checking!)
    T operator[](std::size_t index)
    {
        return arr[index];
    }
private:
    T arr[size]; //internal array
};

その後、次のように使用できます。

array<int, 2> a = { 2, 5 };
int b = a[0]; //'b' == '2'
于 2016-05-30T16:54:05.207 に答える