C++ 如何在将对象添加到矢量时创建对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15802006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create objects while adding them into a vector?
提问by eoLithic
I have a C++ vector. I want the vector to hold a variable number of objects.
我有一个 C++ 向量。我希望向量包含可变数量的对象。
Visual Studio 2012 is giving me an error:
Visual Studio 2012 给我一个错误:
Error: type name is not allowed
From this C++ code:
从这个 C++ 代码:
#include <iostream>
#include <vector>
using namespace std;
class testObject{
private:
int someInt;
public:
testObject(int a){ someInt=a; }
void show() { cout<<someInt<<endl; }
};
int main()
{
vector<testObject> testVector;
cout << "Initial size: " << testVector.size() <<endl;
for ( int i = 0; i < 3; i++ )
testVector.push_back(testObject(3));
cout << "New size: " << testVector.size() << endl;
for ( int j = 0; j < 3; j++ )
testVector[ j ].show();
system("pause");
}
But here's another sample of code that looks the same but it's not working.
但这是另一个看起来相同但不起作用的代码示例。
void Dealer::setNumberOfPlayers( const int tNumber )
{
for ( int i = 0; i < tNumber; i++ )
vectorOfGamers.push_back(Player); // Player is a class that I created
}
Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that? As I know, all objects in vector should be of one type.
我可以创建向量来同时保存庄家、机器人和玩家的对象吗?我怎么做?据我所知, vector 中的所有对象都应该是一种类型。
回答by Cameron
To answer the first part of your question, you must create an object of type Player before you can use it. When you say push_back(Player)
, it means "add the Player classto the vector", not "add an object of type Player to the vector" (which is what you meant).
要回答问题的第一部分,您必须先创建一个 Player 类型的对象,然后才能使用它。当您说 时push_back(Player)
,它的意思是“将 Player类添加到向量中”,而不是“将 Player 类型的对象添加到向量中”(这就是您的意思)。
You can create the object on the stack like this:
您可以像这样在堆栈上创建对象:
Player player;
vectorOfGamers.push_back(player); // <-- name of variable, not type
Or you can even create a temporary object inline and push that (it gets copied when it's put in the vector):
或者您甚至可以内联创建一个临时对象并推送它(当它被放入向量时它会被复制):
vectorOfGamers.push_back(Player()); // <-- parentheses create a "temporary"
To answer the second part, you can create a vector of the base type, which will allow you to push back objects of any subtype; however, this won't work as expected:
要回答第二部分,您可以创建一个基本类型的向量,这将允许您推回任何子类型的对象;但是,这不会按预期工作:
vector<Gamer> gamers;
gamers.push_back(Dealer()); // Doesn't work properly!
since when the dealer object is put into the vector, it gets copied as a Gamer object-- this means only the Gamer part is copied effectively "slicing" the object. You can use pointers, however, since then only the pointer would get copied, and the object is never sliced:
因为当庄家对象被放入向量时,它会被复制为一个玩家对象——这意味着只有玩家部分被有效地“切片”了对象。但是,您可以使用指针,因为这样只会复制指针,并且永远不会对对象进行切片:
vector<Gamer*> gamers;
gamers.push_back(new Dealer()); // <-- Allocate on heap with `new`, since we
// want the object to persist while it's
// pointed to
回答by taocp
Question 1:
问题 1:
vectorOfGamers.push_back(Player)
This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:
这是有问题的,因为您不能直接将类名推送到向量中。您可以将类的对象推送到向量中,也可以将类类型的引用或指针推送到向量中。例如:
vectorOfGamers.push_back(Player(name, id))
//^^assuming name and id are parameters to the vector, call Player constructor
//^^In other words, push `instance` of Player class into vector
Question 2:
问题2:
These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?
These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?
Yes you can. You can create a vector of pointers that points to the base class Gamer
.
A good choice is to use a vector of smart_pointer
, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer
, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?
是的你可以。您可以创建指向基类的指针向量Gamer
。一个不错的选择是使用 的向量smart_pointer
,因此您不需要自己管理指针内存。由于其他三个类是从 派生的Gamer
,基于多态性,您可以将派生类对象分配给基类指针。您可以从这篇文章中找到更多信息:std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?
回答by David Rodríguez - dribeas
You cannot insert a classinto a vector, you can insert an object(provided that it is of the proper type or convertible) of a class though.
你不能将一个类插入到一个向量中,你可以插入一个类的对象(只要它是正确的类型或可转换的)。
If the type Player
has a default constructor, you can create a temporary object by doing Player()
, and that should work for your case:
如果该类型Player
具有默认构造函数,您可以通过执行创建一个临时对象Player()
,这应该适用于您的情况:
vectorOfGamers.push_back(Player());
回答by Casper Beyer
// create a vector of unknown players.
std::vector<player> players;
// resize said vector to only contain 6 players.
players.resize(6);
Values are always initialized, so a vector of 6 players is a vector of 6 valid player objects.
值总是被初始化,所以 6 个玩家的向量是 6 个有效玩家对象的向量。
As for the second part, you need to use pointers. Instantiating c++ interface as a child class
至于第二部分,你需要使用指针。 将 C++ 接口实例化为子类