创建对象向量时,如何将参数传递给Default或Copy Constructor以初始化值? [英] When creating a vector of objects, how to pass arguments to Default or Copy Constructor to initialize values?
问题描述
对于我要为我的C ++类中的项目编写的程序,要求之一是使用构造函数初始化对象中的数据成员.
For a program I'm writing for a project in my C++ class, one of the requirements is to use constructors to initialize data members in objects.
我们还必须读取二进制文件.
We also have to read from binary files.
我选择完成此操作的方法是:
The method I chose to accomplish this was:
// Loads invmast.dat or creates one if none exists
fstream invFile;
invFile.open("invmast.dat", std::fstream::in);
if (!invFile)
{
cout << "File invmast.dat not found, creating a new one." << endl;
invFile.open("invmast.dat", std::fstream::out | std::fstream::app | std::fstream::binary);
if (!invFile)
{
cerr << "Unable to create or open file invmast.dat; exiting." << endl;
exit (EXIT_FAILURE);
}
}
cout << "File invmast.dat opened successfully." << endl;
vector <InventoryItem> invMast;
//vector <InventoryItem>::iterator invMastIterator;
InventoryItem invLoader;
while ( invFile && !invFile.eof())
{
invFile.read(reinterpret_cast<char *>(&invLoader), sizeof(invLoader));
invMast.insert(invMast.begin(), invLoader);
}
我更愿意创建一个对象向量,并将参数传递给副本或默认构造函数,但我似乎找不到找到这种方法的方法.
I'd prefer to create a vector of objects and pass the arguments to the copy or default constructor, but I can't seem to find a way to do this.
有没有办法,或者我需要重新考虑我的方法?
Is there a way, or do I need to rethink my approach?
谢谢!
推荐答案
If you were simply constructing an element, you could use emplace_back
to construct it directly in the vector
:
invMast.emplace_back(some, constructor, parameters);
但是在这里,由于要从原始字节初始化 InventoryItem
,因此您可能只想构造一个对象并将其移至向量中:
But here, since you’re initialising the InventoryItem
from raw bytes, you probably just want to construct an object and move it into the vector:
invFile.read(reinterpret_cast<char *>(&invMast.back()), sizeof(invLoader));
invMast.push_back(std::move(invLoader));
或者默认构造一个元素,然后填充它:
Or default-construct an element and then fill it:
invMast.emplace_back();
invFile.read(reinterpret_cast<char *>(&invMast.back()), sizeof(InventoryItem));
这篇关于创建对象向量时,如何将参数传递给Default或Copy Constructor以初始化值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!