获得奇怪的"预期的主要表达"错误

Rhy*_*den 0 c++ methods

在进行方法调用时,我收到一个非常奇怪的错误:

   /* input.cpp */

#include <ncurses/ncurses.h>
#include "input.h"
#include "command.h"

Input::Input ()
{
    raw ();
    noecho ();
}

Command Input::next ()
{
    char input = getch ();
    Command nextCommand;

    switch (input)
    {
    case 'h':
        nextCommand.setAction (ACTION_MOVELEFT);
        break;
    case 'j':
        nextCommand.setAction (ACTION_MOVEDOWN);
        break;
    case 'k':
        nextCommand.setAction (ACTION_MOVEUP);
        break;
    case 'l':
        nextCommand.setAction (ACTION_MOVERIGHT);
        break;
    case 'y':
        nextCommand.setAction (ACTION_MOVEUPLEFT);
        break;
    case 'u':
        nextCommand.setAction (ACTION_MOVEUPRIGHT);
        break;
    case 'n':
        nextCommand.setAction (ACTION_MOVEDOWNLEFT);
        break;
    case 'm':
        nextCommand.setAction (ACTION_MOVEDOWNRIGHT);
        break;
    case '.':
        nextCommand.setAction (ACTION_WAIT);
        break;
    }


    return nextCommand;
}
Run Code Online (Sandbox Code Playgroud)

和错误:

Administrator@RHYS ~/code/rogue2
$ make
g++ -c -Wall -pedantic -g3 -O0 input.cpp
input.cpp: In member function `Command Input::next()':
input.cpp:21: error: expected primary-expression before '=' token
input.cpp:24: error: expected primary-expression before '=' token
input.cpp:27: error: expected primary-expression before '=' token
input.cpp:30: error: expected primary-expression before '=' token
input.cpp:33: error: expected primary-expression before '=' token
input.cpp:36: error: expected primary-expression before '=' token
input.cpp:39: error: expected primary-expression before '=' token
input.cpp:42: error: expected primary-expression before '=' token
input.cpp:45: error: expected primary-expression before '=' token
make: *** [input.o] Error 1
Run Code Online (Sandbox Code Playgroud)

抱歉没有亚麻布,错误发生在"nextCommand.setAction(...)"行,这完全是奇怪的,因为它们不包含'='.

有任何想法吗?谢谢,

里斯

Jam*_*lis 5

这是我唯一能想到的(没有看到更多代码)会导致这种情况:

全部大写的标识符是宏,定义如下:

#define ACTION_MOVELEFT = 1
#define ACTION_MOVEDOWN = 2
Run Code Online (Sandbox Code Playgroud)

等等.当扩展宏时,最终会得到如下代码:

case 'h':
    nextCommand.setAction (= 1);
    break;
Run Code Online (Sandbox Code Playgroud)

=不用于定义一个宏; 对于类似对象的宏,宏名称后面的所有内容都将一直到结束宏定义的换行符为替换列表的一部分.因此,宏应定义如下:

#define ACTION_MOVELEFT 1
#define ACTION_MOVEDOWN 2
Run Code Online (Sandbox Code Playgroud)

等等.

但是,您应该考虑使用枚举来强制执行类型安全,并避免在不需要使用时使用预处理器:

enum ActionType
{
    ActionMoveLeft,
    ActionMoveDown
};
Run Code Online (Sandbox Code Playgroud)

或者,至少,使用const ints而不是#defines.

  • @paxdiablo:同意.甚至更好,一个枚举. (2认同)