G.P. Burdell
G.P. Burdell

Reputation: 23

Using enums and switch statements in a class

How would I make the following calculator Class work?:

//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

In XCode 3.1.3 I get an "error: syntax error before 'typedef'" and a "warning: declaration does not declare anything" at line 16 of 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

In the implementation, XCode gives me "no declaration of property 'operationType' found in the interface" and "request for member 'operationType' is something not a structure or union." Am I declaring my enums correctly?

Additionally, in switch statements, can I use "case additionOperation" or do I have to use "case 0"?

Upvotes: 2

Views: 4889

Answers (2)

Alex Gray
Alex Gray

Reputation: 16473

I received some interesting answers to similar question I asked here. Check it out, but the gist is..

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

Upvotes: 0

Colin Gislason
Colin Gislason

Reputation: 5589

Move your enum declaration out of the class declaration. You can put it right above. And You may want to rename the typedef to 'OperationType'. Then where you have the declaration now, declare a variable of that type: 'OperationType operationType;'

Upvotes: 4

Related Questions