我定义了一个带有纯虚函数的基类,我想知道是否可以实现 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)制作属于自己类型的新对象。在设计模式术语中,您需要一个工厂方法:
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
或其他合适的智能指针。不太清楚为什么返回许多
Model
(在 vector 中)的readFromFile
是Model
的成员.模型是否以某种方式分层?
关于c++模板或+运算符从指针创建 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152650/