C++/Qt 编码风格——#define 应该放在哪里

标签 c++ qt constants qgraphicsitem

我正尝试在 Qt 中构建一个突破性的游戏克隆。我需要弄清楚我的球与哪种类型的 QGraphicsItem 发生碰撞。例如,如果我的球与墙壁碰撞,球就会弹开,如果它与砖碰撞,它必须反弹并摧毁砖。要找出它是什么类型的 QGraphicsItem,我认为最好的方法可能是覆盖 QGraphicsItem::type()(如果这是,请告诉我方法不对!)。

brick.h 的以下代码中,我将“Brick”的类型设置为 3。现在,值 3 看起来很难跟踪。相反,我宁愿用“#define”来声明一些东西

#include <QGraphicsItem>

//should this #define be here?
//#define BRICK_SPRITE 3

class Brick : public QGraphicsItem
{
public:
    Brick(const QPixmap& p, QGraphicsScene *scene = 0);
    virtual QRectF boundingRect() const;
    virtual void paint( QPainter *painter,
                        const QStyleOptionGraphicsItem *option,
                        QWidget *widget );

    QPainterPath shape() const;

    enum { Type = 3 }; //enum {Type = BRICK_SPRITE}

    int type() const { return Type; }

private:
    QPixmap pixmap;
};

放置语句“#define BRICK_SPRITE 3”的合适位置在哪里?我在项目中还有其他几个文件。我应该将所有定义放在一个单独的头文件中吗?

最佳答案

为什么不直接使用 Type 而不是 3? C++ 中的 enum 可以隐式转换为 int

如果您真的想要一个新名称,我建议您使用const int 变量而不是#define -- 它是类型和命名空间安全,而预处理器宏则不是。

类似于:

class Brick : public QGraphicsItem
{
  static const int BRICK_SPRITE = 3;
  // rest of the class definition
};

根据我能找到的文档,您使用枚举和覆盖 type() 的方法确实是首选方法

关于C++/Qt 编码风格——#define 应该放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10605097/

相关文章:

vba - 在 VBA 中计算常量时溢出

C++ lambda 两次复制构造函数调用

c++ - 如何使 libcurl C++ 调用超时和/或知道调用中何时发生超时

header 中的 C++ 数组声明

java - C++ 中的 HashCodeBuilder

c++ - Qt中的异步函数调用

c++ - 无法将 Map 声明和分配为 const

ios - 如何修复错误 : Binary operator '==' cannot be applied to operands of type 'NSExpression.ExpressionType' and '_'

c++ - QML 在 C++ 加载器中动态插入组件

mysql - sql搜索字符串并获取所有行内容