简体   繁体   中英

What type of variable do I use to store mathematical operator?

I'm trying to put buttons that have operators on them, like / * + , etc. I want to store the operator in such a way that I can use it in an expression, like 1 var 2 = 8

I would like to avoid having to use a different method for each operator, so an operator var would be my best option, I think. Objective-C for iPhone

The usual OO way to do this is to create a class "mathOperator" that has a method "performOp" taking two parameters, then inherit different classes from it that represent the different operations. I'm not an expert in objective-C, so my syntax is probably a bit off, but I think you'd write something like:

result = [var On:arg1 And:arg2];

for example

result = [var On:2 And:3];

would set result to 5 or 6 depending on whether var was set to add or mul . The implementation would look like (again, very roughly):

@interface Add: mathOperator
-(int)On: (int)arg1 And: (int)arg2;
@end

...

@implementation Add
-(int)On:  (int)arg1 And: (int)arg2 {
    return arg1 + arg2;
}

and of course similar for the other operators:

@implementation Mul
-(int)On:  (int)arg1 And: (int)arg2 {
    return arg1 * arg2;
}

Read ch 5 in Cocoa Design Patterns . The approach used is to define "Command" classes that will perform each operation defined as a class method "execute". Then you can dynamically perform the operation by obtaining the appropriate class by using the following

commandName = [NSString stringWithFormat:@"MY%@Command", [commandString capitalizedString]];
commandClass = NSClassFromString(commandName);  
result = [commandClass executeWithXValue:x yValue:y]; 

The way i'd do it is to make methods for each type of arithmatic and pass the numbers into them. Then instead of all that with the variable call the function.

在C语言中没有这样的东西。您必须使用选择器,该选择器调用一种方法来执行您想要的操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM