2010-04-19 61 views
0

製作方法打電話時我發現了一個很奇怪的錯誤:獲得離奇的「預期主表達式」錯誤

/* 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; 
} 

和錯誤:

[email protected] ~/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 

對不起缺乏linenumbers的,錯誤發生在「nextCommand.setAction(...)」行上,考慮到它們不包含'=',這完全是奇怪的。

任何想法? 謝謝,

里斯

+4

全部大小的宏中是否存在標識符,如果是,它們是什麼擴展? – 2010-04-19 01:26:42

回答

5

這是我能想到的唯一的事情(沒有看到更多的代碼),將導致此:

你標識符中的所有大寫的宏定義是這樣的:

#define ACTION_MOVELEFT = 1 
#define ACTION_MOVEDOWN = 2 

等等。當宏然後擴大,你最終像代碼:

case 'h': 
    nextCommand.setAction (= 1); 
    break; 

=不用於定義一個宏;對於類宏對象,宏名後面的所有內容直到結束宏定義的換行符都是替換列表的一部分。所以宏應該定義如下:

#define ACTION_MOVELEFT 1 
#define ACTION_MOVEDOWN 2 

等等。

然而,你應該考慮使用一個枚舉執行類型安全,避免使用預處理時,它不需要使用:

enum ActionType 
{ 
    ActionMoveLeft, 
    ActionMoveDown 
}; 

或者,至少是,使用const int做得相當比#define s。

+1

+1,可能就是這樣。當然,使用const int而不是定義會更聰明,因爲它們也會攜帶類型信息(編譯器對象而不是預處理對象)。 – paxdiablo 2010-04-19 01:37:58

+2

@paxdiablo:同意。甚至更好,枚舉。 – 2010-04-19 01:44:54

+0

謝謝,這是完全正確的。愚蠢的錯誤... – 2010-04-19 01:47:47

2

一般來說,如果您確定錯誤出現在您認爲自己正在使用的行上,並且被投訴的字符不存在,您應該查看預處理程序將這些行擴展到的內容,例如如通過使用gcc -E標誌來查看所述預處理器的輸出。

我懷疑ACTION_MOVELEFT和它的兄弟可能會擴展到意想不到的地方,但只有查看預處理器輸出才能確定地告訴你。

相關問題