没有默认构造函数的类的向量 [英] vector of class without default constructor

查看:66
本文介绍了没有默认构造函数的类的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下类:

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

如何创建 std :: vector< A> 并为构造函数提供一个参数 A :: A(const int&)

How can one create an std::vector<A> and give an argument to the constructor A::A(const int&)?

推荐答案


如何创建类型为 A std :: vector 并给 A 的构造函数一个参数?

How can I create a std::vector of type A and give an argument to A's constructor?



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




我如何将3加到向量?

How would I add 3 to the vector?



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.

这篇关于没有默认构造函数的类的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆