List initialisation in a class constructor in C++

c++ c++14

66 просмотра

2 ответа

I'm new to C++ and how to make constructor for a vector confused me so much. I have a class like this:

class myClass{
public:
    myClass();
    ......
private:
    std::vector<double> myVariable;
    ......
}

and I want to write a constructor for

myClass{1.2, 2.0, 3.1, 4.0};

How do I do this?

Автор: SuperMurloc Источник Размещён: 08.11.2019 11:20

Ответы (2)


6 плюса

Решение

You need a constructor that accepts a std::initializer_list:

explicit myClass(std::initializer_list<double> init) : myVariable(init) {}
Автор: Jesper Juhl Размещён: 20.08.2016 01:09

0 плюса

You can first create a vector, insert elements to it, pass it to the myClass constructor, which assigns it to the class member vector:

class myClass
{
public:
    myClass(const std::vector<double> &src)
        : myVariable(src)
    {
    }

    private:
        std::vector<double> myVariable;
};

int main()
{
    std::vector<double> myvect{1.2, 2.0, 3.1, 4.0};
    myClass obj(myvect);
}
Автор: Swapnil Размещён: 20.08.2016 02:51
Вопросы из категории :
32x32