+= ruby 中的运算符重载 [英] += operator overloading in ruby
问题描述
class Fracpri
attr_accessor:whole, :numer, :denom, :dec, :flofrac
def initialize()
puts "Hey! It's an empty constructor"
end
def getFraction(whole,numer,denom)
@whole=whole
@numer=numer
@denom=denom
end
def showFraction
puts "#{whole} #{numer}/#{denom}"
end
def +=(obj)
if(self.whole+(self.numer.to_f/self.denom.to_f) < obj.whole+(obj.numer.to_f/obj.denom.to_f))
puts "Yes"
else
puts "No"
end
end
end
puts "10 question"
r3=Fracpri.new()
r3.getFraction(1,2,3)
r2=Fracpri.new()
r2.getFraction(4,6,5)
r1=Fracpri.new()
r1.getFraction(2,6,5)
r1 += r2
这是我收到的错误消息:
this is the error message I'm getting:
syntax error, unexpected '=', expecting ';' or '\n'
def +=(obj)
^
syntax error, unexpected keyword_end, expecting end-of-input
建议我如何纠正这个错误,以便我可以执行重载,我需要使用+="运算符添加一个常量
suggest me how to rectify this error so that i can perform overloading,i need to add a constant using "+=" operator
推荐答案
不能覆盖 =
,也不能覆盖诸如 +=
之类的变体.这些是内置的关键字,而不是 方法,例如 +
.
It is not possible to override =
, nor variants such as +=
. These are built in keywords and not methods such as +
.
如果您将补丁从 def +=(obj)
更改为 def +(obj)
,您仍然可以调用 r1 += r2
> 并且它的效果与您修补 +=
的效果相同.这是因为 +=
在幕后调用您修补的 +
方法.
If you change your patch from def +=(obj)
to def +(obj)
, you can still call r1 += r2
and it will have the same effect as if you'd patched +=
. This is because +=
is calling your patched +
method under the hood.
顺便说一下,你的 +
方法实际上并没有返回一个值,所以任何时候你调用 +=
它总是会导致 nil .... 但它看起来这仍然是一个 WIP,所以希望你能解决这个问题.
By the way, your +
method doesn't actually return a value so any time you call +=
it will always result in nil .... but it seems like this is still a WIP so hopefully you can sort that bit out.
这篇关于+= ruby 中的运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!