我有以下课程
class QBoardImages
{
public:
QImage empty_white;
QImage empty_black;
QImage possible_move;
QImage lighter;
QImage choosed;
QImage multiple_move;
QImage blue_pawn;
QImage blue_queen;
QImage blue_skydiver;
QImage red_pawn;
QImage red_queen;
QImage red_skydiver;
QBoardImages();
};
使用构造函数,我有:
QBoardImages::QBoardImages()
{
QDir::setCurrent(QApplication::applicationDirPath());
empty_white.load("images/board/white.png");
empty_black.load("images/board/black.png");
lighter.load("images/board/lighter.png");
choosed.load("images/board/choosed.png");
blue_pawn.load("images/board/blue_pawn.png");
blue_skydiver.load("images/board/blue_skydiver.png");
blue_queen.load("images/board/blue_queen");
red_pawn.load("images/board/red_pawn.png");
red_skydiver.load("images/board/red_skydiver.png");
red_queen.load("images/board/red_queen.png");
possible_move.load("images/board/possible_move.png");
}
当然我想只加载一次这些图片,但我无法做到这一点。加载这些图片的最佳方法是什么?
谢谢大家
答案 0 :(得分:2)
最干净的方法是:
使用引用看起来像这样(如果你愿意,可以使用指针):
class MyOtherClass1 : // ...
{
public:
MyOtherClass1(QBoardImages & boardImages) :
boardImages_(boardImages)
{
// ...
}
private:
QBoardImages & boardImages_;
};
class MyOtherClass2 : // ...
{
// same pattern
}
int main(/* ... */)
{
// ...
QBoardImages boardImages;
MyOtherClass1 object1(boardImages);
MyOtherClass1 object2(boardImages);
// ...
}
替代方法,不太干净但可能最容易实现,因为您不必将boardImages
对象传递给每个构造函数,确实是使用静态方法/对象。单例模式是实现此目的的典型方式,但在您的情况下,问题是您调用QApplication::applicationDirPath()
,这可能无法访问,具体取决于您使用此类的位置。
处理此问题的方法是自己实例化和删除内存,并确保只在这些调用之间使用此类。例如:
// QBoardImages.h
class QBoardImages
{
public:
static QBoardImages * instance();
static void makeInstance();
static void deleteInstance();
QImage empty_white;
// ...
private:
QBoardImages();
static QBoardImages * instance_;
};
// QBoardImages.cpp
QBoardImages * QBoardImages::instance_ = 0;
void QBoardImages::makeInstance(){ instance_ = new QBoardImages; }
void QBoardImages::deleteInstance(){ delete instance_; }
QBoardImages * QBoardImages::instance()
{
if(!instance_)
makeInstance();
return instance_;
}
QBoardImages::QBoardImages()
{
QDir::setCurrent(QApplication::applicationDirPath());
empty_white.load("images/board/white.png");
// ...
}
// main.cpp
int main(int argc, char ** argv)
{
QApplication app(argc, argv);
QBoardImages::makeInstance(); // make sure to call this
// after instantiation of app
// ...
int retValue = app.exec();
QBoardImages::deleteInstance();
return retValue;
}
现在,您可以在调用makeInstance
和deleteInstance
之间的任意位置使用您的图片:
QBoardImages::instance()->empty_white