考虑以下类:
Class A
{
public:
A() = delete;
A(const int &x)
:x(x)
{}
private:
int x;
};
如何创建 std::vector<A>
并为构造函数 A::A(const int&)
提供一个参数?
最佳答案
How can I create a
std::vector
of typeA
and give an argument toA
'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
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
缺少默认构造函数仅意味着您无法执行需要的操作,例如
vector<A> v(10);
v.resize(20);
两者都将默认构造的元素插入 vector 中。
关于c++ - 没有默认构造函数的类 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29920394/