编译器不会在switch语句中识别typedef

时间:2012-12-29 23:45:29

标签: objective-c xcode xcode4

我刚刚开始学习目标c,我正在使用typedef,枚举,switch语句和函数,只是为了更熟悉它们。根据我的理解,这段代码应该都可以工作,但是我得到一个编译错误,我在哪里声明了switch语句,说出“意外类型名称'dinnerPreference':期望表达式。如果我使用typedef定义dinnerPreference,那为什么会发生这种情况。

typedef  enum { pizza = 0, steak = 1, seafood = 2} dinnerPreference;
int main(int argc, const char * argv[])
{

@autoreleasepool {


    dinnerPreference momDinnPref = pizza;
    dinnerPreference myDinnPref  = steak;
    dinnerPreference urDinnPref  = seafood;

    int dinnerPrefFunc ( dinnerPreference x ); {
        NSLog(@"Lets see what this guy wants for dinner");
        dinnerPreference x
        switch( dinnerPreference x ) {
            case pizza:
                NSLog(@"This person wants pizza");
                break;
            case steak:
                NSLog(@"This person wants steak");
                break;
            case seafood:
                NSLog(@"This person wants steak");
                break;
            default:
                NSLog(@"I dunno");
                break;
                return 0;
        };
    }
    dinnerPrefFunc(momDinnPref);
    dinnerPrefFunc(myDinnPref);
    dinnerPrefFunc(urDinnPref);
}
return 0;

2 个答案:

答案 0 :(得分:2)

Objective-C(和C,C ++)不支持在其他函数中声明函数,至少不是你尝试过的方式。尝试按如下方式重新排序代码:

typedef enum { pizza = 0, steak = 1, seafood = 2 } dinnerPreference;

int dinnerPrefFunc ( dinnerPreference x );
int dinnerPrefFunc ( dinnerPreference x )
{
    NSLog(@"Lets see what this guy wants for dinner");
    switch( x )
    {
        case pizza:
            NSLog(@"This person wants pizza");
            break;
        case steak:
            NSLog(@"This person wants steak");
            break;
        case seafood:
            NSLog(@"This person wants steak");
            break;
        default:
            NSLog(@"I dunno");
            break;
    }
    return 0;
}

int main(int argc, const char * argv[])
{

   @autoreleasepool
   {

      dinnerPreference momDinnPref = pizza;
      dinnerPreference myDinnPref  = steak;
      dinnerPreference urDinnPref  = seafood;

      dinnerPrefFunc(momDinnPref);
      dinnerPrefFunc(myDinnPref);
      dinnerPrefFunc(urDinnPref);
   }
   return 0;
}

答案 1 :(得分:1)

这一行错了:

switch( dinnerPreference x ) {

将其更改为:

switch (x) {

还要注意,你还没有初始化x。