c++模板或+运算符从指针创建 vector

标签 c++ templates

我定义了一个带有纯虚函数的基类,我想知道是否可以实现 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)。

我不知道解决方案是否会出现 + operatorModel 上类或使用 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 中)的 readFromFileModel 的成员.模型是否以某种方式分层?

关于c++模板或+运算符从指针创建 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152650/

相关文章:

c++ - 调用基方法模板子类

c++ - 为什么明明一个模板函数实例化不会被内联?

c++ - 我怎样才能使用 GLU_RGBA 或其他 GLU_ 参数?

c++ - vector 的 vector ,堆与栈 (C++)

c++ - 使用 QuaZip 在 Mac 上提取 .app

c++ - 成员函数不能访问私有(private)成员

C++ 区分结构相同的类

c++ - 同时专门化外部和嵌套类

c++ - 奇怪的 iostream 编译错误

c++ - 在 C++ 中检测一个或两个的补码架构?