#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();
}
327

被折叠的 条评论
为什么被折叠?



