OK this may be the dumb question of the day, but supposing I have a class with :
NSDecimalNumber *numOne = [NSDecimalNumber numberWithFloat:1.0]; NSDecimalNumber *numTwo = [NSDecimalNumber numberWithFloat:2.0]; NSDecimalNumber *numThree = [NSDecimalNumber numberWithFloat:3.0];
Why can't I have a function that adds those numbers:
- (NSDecimalNumber *)addThem { return (self.numOne + self.numTwo + self.numThree); }
I apologize in advance for being an idiot, and thanks!
You can't do what you want becuase neither C nor Objective C have operator overloading. Instead you have to write:
- (NSDecimalNumber *)addThem { return [self.numOne decimalNumberByAdding: [self.numTwo decimalNumberByAdding:self.numThree]]; }
If you're willing to play dirty with Objective-C++ (rename your source to .mm), then you could write:
NSDecimalNumber *operator + (NSDecimalNumber *a, NSDecimalNumber *b) { return [a decimalNumberByAdding:b]; }
Now you can write:
- (NSDecimalNumber *)addThem { return self.numOne + self.numTwo + self.numThree; }
Go C++!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With