c 继承方式高内聚read write function操作
墨初 知识笔记 123阅读
code class="prism language-cpp">#include <iostream>#include <fstream>#include <vector>using namespace std;struct BaseDevice{ BaseDevice(const std::string sType, const std::string sApplication) : strType(sType), strApplication(sApplication) {} virtual ~BaseDevice(); std::string strType; std::string strApplication;};BaseDevice::~BaseDevice() {}struct GetDeviceInfor : public BaseDevice{ GetDeviceInfor(const std::string sType, const std::string sApplication) : BaseDevice(sType, sApplication) {} virtual ~GetDeviceInfor();};GetDeviceInfor::~GetDeviceInfor(){}template<class T1>struct SetDeviceInfor : public BaseDevice{ SetDeviceInfor(const std::string sType, const std::string sApplication, T1 iValues):BaseDevice(sType, sApplication), iValues(iValues) {} ~SetDeviceInfor() {} T1 iValues;};int main(int argc, char/span> argv){ std::vector<std::shared_ptr<BaseDevice>> vecDeviceInfor { std::make_shared<GetDeviceInfor>(TemputerData, FirstScreen), std::make_shared<GetDeviceInfor>(RealValue, MeasurmentMode), std::make_shared<SetDeviceInfor<std::string>>(MachineValue, MaintainerMode, 45) }; for (auto pDeviceInfor : vecDeviceInfor) { if (pDeviceInfor) { std::shared_ptr<GetDeviceInfor> pGetDeviceTemoInfor std::dynamic_pointer_cast<GetDeviceInfor>(pDeviceInfor); if (pGetDeviceTemoInfor ! nullptr) { std::cout << pGetDeviceTemoInfor->strApplication << std::endl; } std::shared_ptr<SetDeviceInfor<std::string>> pSetDeviceTemoInfor std::dynamic_pointer_cast<SetDeviceInfor<std::string>>(pDeviceInfor); if (pSetDeviceTemoInfor ! nullptr) { std::cout << pSetDeviceTemoInfor->strApplication << std::endl; std::cout << pSetDeviceTemoInfor->iValues << std::endl; } } else { std::cout << empty container! << std::endl; } }}/pre>
标签: