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?
您需要一个接受std::initializer_list
的构造std::initializer_list
:
explicit myClass(std::initializer_list<double> init) : myVariable(init) {}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.