[英]How to dynamically instantiate a class with parameterized constructor using std::vector?
I want to dynamically instantiate the object using vector, However, I don't know how to pass the parameter to the constructor.我想使用向量动态实例化对象,但是,我不知道如何将参数传递给构造函数。
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
class Player {
public:
Player(int id, string name)
: p_id(id)
, p_name(name)
{
}
public:
int p_id;
string p_name;
};
int main() {
vector<Player> player; **//How to instantiate the object with parametrized constructor**
player.resize(sizeof(player));
return 0;
}
I assume, you may want to look toward this:我想,你可能想看看这个:
class Player {
public:
Player() = default;
Player(int id, string name): p_id(id), p_name(name) {}
private:
int p_id;
string p_name;
};
int main() {
vector<Player> players;
// construct a Player from an int and a string
players.emplace_back(33, "Foo");
}
Here, we use a std::vector
member functionemplace_back()
, which constructs an object inside (at the back) the vector.在这里,我们使用std::vector
成员函数emplace_back()
,它在向量内部(在后面)构造一个对象。
There are other thing(s) to note in your code:您的代码中还有其他需要注意的事项:
players.resize(sizeof(players)); // Is nonsensical
You should check the documentation on std::vector::resize
and the documentation on sizeof()
.您应该检查文档上std::vector::resize
和文件上sizeof()
In short, we can use resize(n)
to change the amount of elements in the container.简而言之,我们可以使用resize(n)
来改变容器中元素的数量。
We can either increase the number of elements , by providing such n
that is greater than the current size()
.我们可以通过提供大于当前size()
n
来增加元素的数量。 In which case, additional default-inserted elements are appended.在这种情况下,会附加其他默认插入的元素。
Or decrease the number of elements in the container by providing smaller n
.或者通过提供较小的n
减少容器中的元素数量。 In which case, the content of the container is reduced to its first n
elements, removing those beyond (and destroying them).在这种情况下,容器的内容被减少到它的前n
元素,删除那些超出(并销毁它们)。
Note, that this function alters the actual contents of a container:请注意,此函数会更改容器的实际内容:
players.emplace_back(11, "Foo");
players.emplace_back(22, "Bar");
players.emplace_back(33, "Buz");
players.resize(2); // Now, players.size() == 2
// ...and there are no Buz among the players
That's why passing the sizeof(players)
to resize()
is meaningless, especially when we consider that the sizeof()
returns a number of bytes .这就是为什么将sizeof(players)
传递给resize()
是没有意义的,尤其是当我们考虑到sizeof()
返回多个字节时。
If you want to have a vector
with some number of pre-constructed Player
objects in it, you should use vector's fill constructor :如果你想有一个vector
与一些数量的预构建的Player
在它的对象,你应该使用矢量的填充构造函数:
// Ten objects of class Player
vector<Player> players(10, Player(0, ""));
// Ten default constructed objects of type Player
vector<Player> players(10); // Player has to have a default constructor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.