你有木有遇到过这种情况,感觉自己写的程序没问题,但一运行就是会崩,而且怎么都找不出来原因,胡乱改了一会(其实也不是胡乱啦)它又好了,发现也没有改什么关键性的东西,所以又把代码改成和崩溃时候一模一样的代码,发现它就这样莫名其妙的好了!!
我经常被这种问题搞的又气又笑。自始至终都不知道到底哪里出了问题。
今天又遇到这种情况,好在今天发现了原因。
这篇文章并不能概括以上所说的情况,但却是以上情况中的一种。
问题是从这里开始的(我只列出问题代码,其余代码省略):
class SpiderCard : public QWidget
{
Q_OBJECT
public:
explicit SpiderCard(QWidget *parent = 0);
private:
const int CARDWIDTH; // 就是这两个变量啦
const int CARDHEIGHT; // 就是这两个变量啦
};
我在这里定义了 2 个 const 类型的 int 变量,然后我在定义构造函数时这样给它初始化(因为 const 变量比 define 好很多,这是 C++ 对 C 语言的改进):
#include "spidercard.h"
SpiderCard::SpiderCard(QWidget *parent) :
QWidget(parent)
,CARDWIDTH(70) // 虽然 C++ 11 允许在 .h 里边给变量赋值了
,CARDHEIGHT(107) // 但是 推荐的方式还是这样写比较好
{
// 因为 const 变量只能初始化不能赋值,所以在这里给它赋值是万万不行滴
}
这样程序就崩了。我是怎么调试都找不到原因,我还以为我记错了不能这样写呢。我就暂时改成了下面这样的,问题暂时过去了:
#include "spidercard.h"
const CARDWIDTH = 70;
const CARDHEIGHT = 107;
SpiderCard::SpiderCard(QWidget *parent) :
QWidget(parent)
{
}
但是,一会更恶劣的问题又出现了:
#include "spidercard.h"
#include <QPropertyAnimation>
const CARDWIDTH = 70;
const CARDHEIGHT = 107;
SpiderCard::SpiderCard(QWidget *parent) :
QWidget(parent)
{
QPropertyAnimation *animation = new QPropertyAnimation(this); // 这样写是好的
}
我这样定义 animation 变量是可以的,但是我把它定义在 .h 文件里然后在 .cpp 文件里 new 出来就不行了:
// .h 文件
class QPropertyAnimation;
class SpiderCard : public QWidget
{
Q_OBJECT
public:
explicit SpiderCard(QWidget *parent = 0);
private:
QPropertyAnimation *animation; // 我在这里定义
signals:
public slots:
};
// .cpp 文件
#include "spidercard.h"
#include <QPropertyAnimation>
const CARDWIDTH = 70;
const CARDHEIGHT = 107;
SpiderCard::SpiderCard(QWidget *parent) :
QWidget(parent)
{
animation = new QPropertyAnimation(this); // 在这里 new 出来程序就会崩
}
这时我意识到问题不是出在代码上了,可能是编译器做了优化的问题,我猜测是它检测变量名没变的情况下为了速度,再次编译的时候就不会重新编译出 .o 文件,还用之前编译的 .o 文件,所以出了冲突,我把生成的文件夹全删了,重新编译果然好了。^_^
所以我把之前的 const 变量又写成风格比较好的形式,也没问题啦:
// .h 文件
class QParallelAnimationGroup;
class SpiderCard : public QWidget
{
Q_OBJECT
public:
explicit SpiderCard(QWidget *parent = 0);
private:
QPropertyAnimation *animation;
const int CARDWIDTH;
const int CARDHEIGHT;
signals:
public slots:
};
// .cpp 文件
#include "spidercard.h"
#include <QPropertyAnimation>
SpiderCard::SpiderCard(QWidget *parent) :
QWidget(parent)
,CARDWIDTH(70)
,CARDHEIGHT(107)
{
animation = new QPropertyAnimation(this);
}
希望以后再遇到这种问题的时候往这方面考虑一下可能会省去很多宝贵时间。