我有一个带有纯虚函数的已定义基类,我想知道是否可以通过以下方式实现下面的readFromFile()
函数:
class Model {
time_t changedateTime;
virtual void writeToFile(std::string fileName, Model* model) = 0;
// Is that possible, a vector of its own class pointer
virtual std::vector<Model*> readFromFile(std::string fileName) = 0;
}
模型的实际实现:
class Customer : public Model {
std::string Name;
std::string Address;
}
要么
class OrderItem : public Model {
std::string Item;
std::string Price;
}
并且比写入文件和读取文件实现:
void Model::writeToFile(std::string fileName, Model* model)
{
// .... opens the file....
// ... append model to the end of file....
// ... close file...
}
std::vector(Model*) Model::readFromFile(std::string fileName, Model* model)
{
// .... opens the file fileName...
// ...get several lines of data to add to returning vector...
std::vector(Model*) returnVector;
Model* newModel = new Something // <--- How can I create here a new class of
// the type I want to add to the vector??????
}
我被困在从继承的模型类型创建新对象并将其添加到要返回的 vector 中(
returnVector
)。我不知道该解决方案是否会在
+ operator
类上定义Model
或使用C++ template
或什至其他。.我来自C#,在这里我会很容易地使用<T>
泛型类型。实际上,我需要帮助以进一步发展,并非常感谢专家的评论。
最佳答案
由于您希望Model
成为常见的基类,因此模板并不是真正的解决之道。您需要教课以制作自己类型的新对象。在设计模式术语中,您需要一种工厂方法:
class Model {
time_t changedateTime;
virtual void writeToFile(std::string fileName, Model* model);
virtual std::vector<Model*> readFromFile(std::string fileName);
virtual Model* createNewObject() const = 0;
}
std::vector(Model*) Model::readFromFile(std::string fileName, Model* model)
{
//.... opens the file fileName...
//...get several lines of data to add to returning vector...
std::vector<Model*> returnVector;
Model* newModel = createNewObject();
// proceed normally
}
Model* Customer::createNewObject() const
{
return new Customer;
}
一些注意事项:
std::unique_ptr
或其他合适的智能指针。 readFromFile
是Model
的成员,它返回(在 vector 中)许多Model
s。模型是以某种方式分层的吗?