#define出错

时间:2011-03-28 02:02:58

标签: c++ global-variables constants c-preprocessor

我有一个包含许多#define语句的文件,例如 -

#ifndef UTILITY_H
#define UTILITY_H
#define BUMP 7;
#define WHEEL_DROPS 7;
#define WALL 8;
#define CLIFF_LEFT 9;
#define CLIFF_FRONT_LEFT 10;
#define CLIFF_FRONT_RIGHT 11;
#define CLIFF_RIGHT 12;
#define VIRTUAL_WALL 13;
...
... 
#endif

该列表继续介绍约42种不同的值。我将此文件包含在我的其他文件中,但每当我尝试使用其中一个常量时,我​​都会收到错误。对于一个具体的例子,我尝试做 -

Sensor_Packet temp;
temp = robot.getSensorValue(BUMP); //line 54
cout<<temp.values[0]<<endl;

我得到的错误是 -

main.cpp:54: error: expected ‘)’ before ‘;’ token
main.cpp:54: error: expected primary-expression before ‘)’ token
main.cpp:54: error: expected ‘;’ before ‘)’ token

我不明白为什么我会收到这些错误,因为已经定义了BUMP。当我尝试使用switch语句时,也会发生这种情况,其中case是定义 -

switch(which) {
case BUMP:
    //do stuff
case CLIFF_LEFT:
   //do stuff
}

关于使用#define,我有什么遗漏吗?我认为我所要做的就是定义一个常量然后我就可以调用它。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:9)

仔细查看您的#define

#define BUMP 7;

这告诉预处理器将BUMP替换为7;。请注意,宏定义包括分号!

所以你的代码实际上对编译器来说是这样的:

Sensor_Packet temp;
temp = robot.getSensorValue(7;);
cout<<temp.values[0]<<endl;

// ...

switch(which)
{
case 7;:
    // do stuff
case 9;:
    //do stuff
}

这显然是语法错误。要解决此问题,请删除#define语句中的分号。

但是在C ++中,你应该使用const intenum来代替#define s。以下是一些可能的示例:

enum CliffPositions
{
    CLIFF_LEFT  = 9,
    CLIFF_FRONT_LEFT = 10,
    CLIFF_FRONT_RIGHT = 11,
    CLIFF_RIGHT = 12,
};

enum WallType
{
    WALL = 8,
    VIRTUAL_WALL = 13;
}

const int BUMP = 7;
const int WHEEL_DROPS = 7;

// etc ...

这种方式更受欢迎,因为与#define不同,const intenum尊重范围且更加类型安全。

答案 1 :(得分:2)

去掉分号,你应该好好去。