简体   繁体   English

没有默认构造函数的类的向量

[英]vector of class without default constructor

Consider the following class:考虑以下类:

Class A
{
    public:
       A() = delete;
       A(const int &x)
       :x(x)
       {}
    private:
       int x;
};

How can one create an std::vector<A> and give an argument to the constructor A::A(const int&) ?如何创建std::vector<A>并为构造函数A::A(const int&)

How can I create a std::vector of type A and give an argument to A 's constructor?如何创建A类型的std::vector并为A的构造函数提供参数?

std::vector<A> v1(10, 42);  // 10 elements each with value 42
std::vector<A> v2{1,2,3,4}; // 4 elements with different values

How would I add 3 to the vector?我如何将 3 添加到向量中?

v.emplace_back(3);          // works with any suitable constructor
v.push_back(3);             // requires a non-explicit constructor

The lack of a default constructor only means you can't do operations that need one, like缺少默认构造函数仅意味着您无法执行需要的操作,例如

vector<A> v(10);
v.resize(20);

both of which insert default-constructed elements into the vector.两者都将默认构造的元素插入到向量中。

Templates are not instantiated in one go : they only instantiate what is needed.模板不是一次性实例化的:它们只实例化需要的东西。 A satisfies all the conditions for the following (constructing an empty vector) to be valid : A满足以下(构造空向量)有效的所有条件:

std::vector<A> v;

However, as A does not have a default constructor, the following (creating a vector with default-initialized content) would fail :但是,由于A没有默认构造函数,因此以下(创建具有默认初始化内容的向量)将失败:

std::vector<A> v(100);

And that's a good thing.这是一件好事。 However, valid methods will be instantiated fine :但是,有效的方法将被很好地实例化:

v.emplace_back(42);

The trick is in how you add elements into the vector and what member functions of the vector you use.诀窍在于如何将元素添加到向量中以及使用向量的哪些成员函数。

std::vector<A> v;
v.emplace_back(3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM