#include <QCoreApplication>
#include <iostream>using namespace std;class XmCom
{
public:void ComByXm(){cout << "XM電源適配器只適用于小米筆記本電腦" << endl;}
};class LxCom
{
public:virtual void ComByLx() = 0;virtual ~LxCom() {};
};class XmToLx : public LxCom, XmCom
{void ComByLx(){this->ComByXm();cout << "將小米電源適配器轉換成聯想電源適配器" << endl;}
};class Com
{
public:Com(LxCom *lxx){this->m_lx = lxx;}void Work(){cout <<"XM電源適配器可以用在LX筆記本電腦上了,LX筆記本可以正常工作了 !" << endl;}void Change(){this->m_lx->ComByLx();}private:LxCom *m_lx = new XmToLx();
};int main(int argc, char *argv[])
{LxCom *_lx = new XmToLx();Com *com = new Com(_lx);com->Change();com->Work();delete _lx;delete com;QCoreApplication a(argc, argv);// Set up code that uses the Qt event loop here.// Call a.quit() or a.exit() to quit the application.// A not very useful example would be including// #include <QTimer>// near the top of the file and calling// QTimer::singleShot(5000, &a, &QCoreApplication::quit);// which quits the application after 5 seconds.// If you do not need a running Qt event loop, remove the call// to a.exec() or use the Non-Qt Plain C++ Application template.return a.exec();
}
對內存泄漏部分的修改:
#include <memory>class Com {
public:explicit Com(std::unique_ptr<LxCom> lxx) : m_lx(std::move(lxx)) {}void Work() { /* ... */ }void Change() { m_lx->ComByLx(); }private:std::unique_ptr<LxCom> m_lx;
};
內存管理優化版(使用智能指針):
#include <QCoreApplication>
#include <iostream>
#include <memory>using namespace std;class XmCom
{
public:void ComByXm(){cout << "XM電源適配器只適用于小米筆記本電腦" << endl;}
};class LxCom
{
public:virtual void ComByLx() = 0;virtual ~LxCom() = default;
};class XmToLx : public LxCom, XmCom
{void ComByLx() override{this->ComByXm();cout << "將小米電源適配器轉換成聯想電源適配器" << endl;}
};class Com
{
public:explicit Com(std::unique_ptr<LxCom> lxx) : m_lx(std::move(lxx)) {}// Com(LxCom *lxx)// {// this->m_lx = lxx;// }void Work(){cout <<"XM電源適配器可以用在LX筆記本電腦上了,LX筆記本可以正常工作了 !" << endl;}void Change(){this->m_lx->ComByLx();}private:unique_ptr<LxCom> m_lx;//LxCom *m_lx = new XmToLx();
};int main(int argc, char *argv[])
{auto com = std::make_unique<Com>(std::make_unique<XmToLx>());com->Change();com->Work();QCoreApplication a(argc, argv);return a.exec();// Set up code that uses the Qt event loop here.// Call a.quit() or a.exit() to quit the application.// A not very useful example would be including// #include <QTimer>// near the top of the file and calling// QTimer::singleShot(5000, &a, &QCoreApplication::quit);// which quits the application after 5 seconds.// If you do not need a running Qt event loop, remove the call// to a.exec() or use the Non-Qt Plain C++ Application template.return a.exec();
}