0
我想根據用戶是否用-m或-f調用程序來初始化特定的子類。根據輸入初始化特定的子類
我寫的界面是這樣的:
class DatabaseInterface {
public:
virtual std::vector<Newsgroup> list_newsgroups() = 0;
virtual std::vector<Article> list_articles(const size_t article_id) const = 0;
virtual bool create_newsgroup(const std::string& newsgroup_name) = 0;
virtual bool create_article(const size_t newsgroup_id, const std::string& title, const std::string& author, const std::string& text) = 0;
virtual bool delete_newsgroup(const size_t newsgroup_id) = 0;
virtual std::pair<int,Article> get_article(const size_t newsgroup_id, const size_t article_id) const = 0 ;
virtual int delete_article(const size_t newsgroup_id, const size_t article_id) = 0;
};
在我的類,它使用的數據庫,我有這些行:
string file_memory;
DatabaseMemory db;
try {
file_memory = argv[2];
if(file_memory.compare("-file") == 0 || file_memory.compare("-f") == 0) {
DatabaseFile db;
cout << file_memory << endl;
} else if (file_memory.compare("-memory") == 0 || file_memory.compare("-m") == 0) {
DatabaseMemory db;
} else {
cerr << "Specify saving on disk with '-f' or in memory with '-m' " << endl;
exit(1);
}
} catch (exception& e) {
cerr << "Specify saving on disk or in memory" << endl;
exit(1);
}
正如你所看到的我試圖初始化派生的DatabaseMemory,只是爲了討好編譯器,但是,這看起來像是一種劣質的方法。我會如何改善這一點?
我希望能夠寫類似
DatabaseInterface db;
if(file_memory == "-m") {
db = DatabaseMemory();
} else if (file_memory == "-f") {
db = DatabaseFile();
} else {
exit(1);
}
//.... do stuff
我如何去這樣做呢?在這一點上,我的界面沒有給我任何東西。我想我可能錯過了在這裏使用它的要點。
由於更換
make_unique
,會嘗試。雖然,它不應該與make_unique相反嗎?例如,如果「-f」則使DatabaseFile具有唯一性,反之亦然?問候 – enrm 2015-04-02 12:53:39@enrm:這會更有意義。我只是複製了最終代碼片段中的標誌,而沒有太多考慮它們可能的含義。 – 2015-04-02 13:16:56
使用make_unique需要什麼編譯器?我使用g ++ 4.9.2,它不能識別make_unique .. – enrm 2015-04-02 13:37:32