2010-06-09 136 views
2

我怎么会做如下计算类的工作?:使用枚举和switch语句中的一类

//Calculator.h 

#import <Cocoa/Cocoa.h> 

@interface Calculator : NSObject { 
    float initialNumber, operandNumber; 
    typedef enum{ 
    additionOperation, 
    subtractionOperation, 
    multiplicationOperation, 
    divisionOperation 
    }operationType; 
} 

@property(readwrite) float initialNumber, operandNumber; 
@property(readwrite) enum operationType; //Line 16 

- (float) doOperation; 

@end 

在Xcode 3.1.3我得到一个“错误:‘之前的typedef’语法错误”和“警告:申报不申报任何东西“在Calculator.h

//Calculator.m 

#import "Calculator.h" 

@implementation Calculator 
@synthesize initialNumber, operandNumber, operationType; 

-(float) doOperation{ 
    switch (self.operationType){ //Line 9 
     case 0: 
      return self.initialNumber + self.operandNumber; 
      break; 
     case 1: 
      return self.initialNumber - self.operandNumber; 
      break; 
     case 2: 
      return self.initialNumber * self.operandNumber; 
      break; 
     case 3: 
      return self.initialNumber/self.operandNumber; 
      break; 
     default: 
      return 0; 
      break; 
    } 
} 

@end 

在执行第16行,的XCode给我‘没有在接口中发现的特性‘operationType’宣言’和”请求成员的operationType“是不是结构或联盟。“我是否正确地声明了我的枚举?

此外,在switch语句中,我可以使用“case additionOperation”还是必须使用“case 0”?

+2

在您的switch语句中,使用您在'enum'中提供的名称而不是它们代表的值。 – dreamlax 2010-06-09 13:28:57

回答

4

将您的枚举声明移出类声明。你可以把它放在上面。你可能想要将typedef重命名为'OperationType'。然后,你现在声明的地方,声明一个该类型的变量:'OperationType operationType;'

+0

谢谢科林,那就做到了! – 2010-06-09 14:11:00

0

我收到了一些有趣的答案to similar question I asked here。检查出来,但要点是......

"typedefs such as NSViewWidthSizable are actually bitmasks, which allow the nice ORing operations you so enjoy"