2015-05-10 87 views
2

我有純虛函數和我想一個定義的基類創建矢量知道如果其能夠實現以下功能的readFromFile()以下列方式:C++模板或+操作員從指針

class Model { 
    time_t changedateTime; 

    virtual void writeToFile(std::string fileName, Model* model) = 0; 
    virtual std::vector<Model*> readFromFile(std::string fileName) = 0; <-- Is that possible, a 
                      vector of its own class pointer 
} 

型號的真正實現:

class Customer : pubic Model { 
    std::string Name; 
    std::string Address; 
} 

class OrderItem : pubic 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?????? 

} 

I'm stucked在這裏創作從繼承的模型類型的新對象,將其添加到矢量返回(returnVector)。

我不知道如果解決方案會defing一個+ operatorModel類,或使用C++ template,甚至是別的東西.. I'm從C#來了,在那裏我會很容易在這裏使用<T>泛型類型。

事實上,我需要幫助才能更進一步,非常感謝專家的評論。

+0

是的。糾正。 – Mendes

回答

2

既然你想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(在一個向量中)是Model的成員,因此不太清楚。模型是否以某種方式分層?

+0

不錯的解決方案...'std :: unique_ptr'會出現在所有'Model *指針'中,對吧?另外,'readFromFile'屬於'Model',因爲文件的每一行都將包含一個差異模型類型,行:'Customer,John,第56 Av'和'OrderItem,338484,34.95'。我需要他們在同一個文件的其他原因(遺產)... – Mendes

+0

@Mendez它不會*全部*他們。只有那些真正擁有他們指向的東西的人。請仔細閱讀關於智能指針和所有權的更多信息。 – Angew

-2

我對這個問題確切地不清楚。在諸如這些情況下的對象生成的標準方法是「抽象工廠」實現。您仍然需要確定如何確定要創建的對象類型。所有說的有庫實現提供你正在尋找的功能。