gpt4 book ai didi

c++ - #define 错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:20:14 24 4
gpt4 key购买 nike

我有一个包含许多 #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 有什么我遗漏的吗?我以为我所要做的就是定义一个常量,然后我就可以调用它了。感谢您的帮助。

最佳答案

仔细看看你的#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 s 代表常量而不是 #define。以下是一些可能的示例:

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 尊重范围并且类型安全。

关于c++ - #define 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com