Andrei
Andrei

Reputation: 25

Constructor with array parameters

I want to make a constructor with array and array size so I can call the object using this: Multime m1 = Multime({1, 2, 3}, 3); Or should I use std::vector instead?

class Multime
{
private:
    int elemente[100];
    int size;
public:
    Multime(){}
    Multime(int el[50], int s){
        this -> size = s;
        for(int i = 0; i < this -> size; i++)
            this -> elemente[i] = el[i];
    }
};

int main()
{
    Multime m1 = Multime({1, 2, 3}, 3);
    return 0;
}

And i'm getting No matching constructor for initialization of 'Multime'

Upvotes: 1

Views: 971

Answers (2)

Blaze
Blaze

Reputation: 16876

Or should I use std::vector instead?

That's a great idea.

class Multime
{
private:
    std::vector<int> elemente;
public:
    Multime() {}
    Multime(std::vector<int> el) : elemente(std::move(el)) {}
};

int main()
{
    Multime m1 = Multime({ 1, 2, 3 });
    return 0;
}

Upvotes: 2

Adrien Givry
Adrien Givry

Reputation: 965

If you want your class to be able to contain a varying number of elements (Defined at compile time), you can try:

#include <array>

template <size_t _Size>
class Multime
{
private:
    int elemente[_Size];
public:
    Multime() {}

    Multime(const std::array<int, _Size>& p_elements)
    {
        for (int i = 0; i < _Size; ++i)
            this->elemente[i] = p_elements[i];
    }
};

int main()
{
    Multime<3> m1({1, 2, 3});
    return 0;
}

You can also directly store an std::array into your class, so the construction is cleaner

#include <array>

template <size_t _Size>
class Multime
{
private:
    std::array<int, _Size> elemente;
public:
    Multime() {}
    Multime(const std::array<int, _Size>& p_elements) : elemente(p_elements) {}
};

int main()
{
    Multime<3> m1({1, 2, 3});
    return 0;
}

Upvotes: 0

Related Questions