我正在處理一個很大程度上不是我創建的專案,但我的任務是為其添加一些功能。目前,有一個設備類有一個成員變數,負責存盤有關存盤位置的資訊,設定如下:
device.hpp
class device {
public:
// Stuff
private:
// Stuff
StorageInfo storage_info_;
// Even more stuff
}
StorageInfo.hpp
class StorageInfo {
public:
void initializeStorage();
void updateStorageInfo();
int popLocation();
int peakLocation();
uint16_t totalSize();
uint16_t remainingSize();
// More declarations here
private:
//Even more stuff here
}
我的任務是實作不同的存盤選項,以便可以在兩者之間切換。這個新存盤選項具有的資訊功能將與初始存盤選項相同,但檢索該資訊的實作卻大不相同。為了保持干凈并在未來幾年更容易維護此應用程式,它們確實需要在兩個不同的檔案中定義。然而,這在內部產生了一個問題device.cpp,以及在呼叫 StorageInfo 類的每個其他檔案中。如果我創建兩個單獨的成員變數,每個型別的存盤一個,那么我不僅需要插入一百萬個不同的 ifelse 陳述句,而且我有可能在建構式中遇到初始化問題。我想做的是有一個成員變數,它有可能保存任一存盤選項類。像這樣的東西:
StorageInfoA.hpp
class StorageInfoA: StorageInfo {
public:
void initializeStorage();
void updateStorageInfo();
int popLocation();
int peakLocation();
uint16_t totalSize();
uint16_t remainingSize();
// More declarations here
private:
//Even more stuff here
}
StorageInfoB.hpp
class StorageInfoB: StorageInfo {
public:
void initializeStorage();
void updateStorageInfo();
int popLocation();
int peakLocation();
uint16_t totalSize();
uint16_t remainingSize();
// More declarations here
private:
//Even more stuff here
}
device.hpp
class device {
public:
// Stuff
private:
// Stuff
StorageInfo storage_info_;
// Even more stuff
}
device.cpp
//Somewhere in the constructor of device.cpp
if(save_to_cache){
storage_info_ = StorageInfoA();
} else {
storage_info_ = StorageInfoB();
}
// Then, these types of calls would return the correct implementation without further ifelse calls
storage_info_.updateStorageInfo();
但是,我知道 cpp 絕對討厭任何動態型別,所以我真的不知道如何實作這一點。這種事情甚至可能嗎?如果沒有,有沒有人知道一種類似的方法來實作這一點,它適用于 cpp 的輸入規則?
uj5u.com熱心網友回復:
你在正確的軌道上,但你必須學習如何使用多型。在您的示例中,您需要進行以下修復:
在基類中,將所有函式設為虛擬,并添加一個虛擬解構式:
class StorageInfo {
public:
virtual ~StorageInfo(){}
virtual void initializeStorage();
//...
};
公開您的遺產:
class StorageInfoA: public StorageInfo {
不是StorageInfo按值保存,而是將其保存在智能指標中:
class device {
private:
std::unique_ptr<StorageInfo> storage_info_;
};
device 建構式看起來像
//Somewhere in the constructor of device.cpp
if(save_to_cache){
storage_info_ = std::make_unique<StorageInfoA>();
} else {
storage_info_ = std::make_unique<StorageInfoB>();
}
最后,您將像使用普通指標一樣使用它:
storage_info_->updateStorageInfo();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314618.html
上一篇:在子類中覆寫__new__以創建特定的父類實體是反模式嗎?
下一篇:繼承類看不到基類
