如何添加 NSDecimalNumbers?
好吧,这可能是今天最愚蠢的问题,但假设我有一堂课:
NSDecimalNumber *numOne = [NSDecimalNumber numberWithFloat:1.0];
NSDecimalNumber *numTwo = [NSDecimalNumber numberWithFloat:2.0];
NSDecimalNumber *numThree = [NSDecimalNumber numberWithFloat:3.0];
为什么我不能有一个函数来添加这些数字:
- (NSDecimalNumber *)addThem {
return (self.numOne + self.numTwo + self.numThree);
}
我提前为自己是个白痴而道歉,谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能做你想做的事,因为 C 和 Objective C 都没有运算符重载。相反,你必须这样写:
如果你愿意玩弄 Objective-C++(将源代码重命名为 .mm),那么你可以这样写:
现在你可以这样写:
Go C++!
You can't do what you want becuase neither C nor Objective C have operator overloading. Instead you have to write:
If you're willing to play dirty with Objective-C++ (rename your source to .mm), then you could write:
Now you can write:
Go C++!
NSDecimalNumber 是一个 Objective C 类,实例化时会生成一个包含数字的对象。您只能通过方法访问对象(以及一般对象)。 Objective C 没有办法直接表达对象的算术,因此您需要进行以下三个调用之一:
NSDecimalNumber is an Objective C class which, when instantiated, produces an object which contains a number. You access the object (and objects in general) through methods only. Objective C doesn't have a way to directly express arithmetic against objects, so you need to make one of three calls:
请参阅 NSDecimalAdd 函数(以及 NSDecimalMultiply、NSDecimalDivide、NSDecimalSubtract)。
See
NSDecimalAdd
function (as well as NSDecimalMultiply, NSDecimalDivide, NSDecimalSubtract).您可以:
您的示例的问题在于 self.numOne 实际上在位级别上是指向对象的指针。所以你的函数将返回一些随机内存位置,而不是总和。
如果 Objective-C 支持 C++ 风格的运算符重载,那么有人可以在应用于两个 NSDecimalNumber 对象时定义
+
作为decimalNumberByAdding:
的别名。但事实并非如此。You can:
The problem with your example is that what self.numOne really is at a bit level is a pointer to an object. So your function would return some random memory location, not the sum.
If Objective-C supported C++-style operator overloading, someone could define
+
when applied to two NSDecimalNumber objects as an alias todecimalNumberByAdding:
. But it doesn't.