您的位置:首页 > 编程语言 > Ruby

Ruby运算符重载

2015-10-16 15:55 429 查看

Ruby运算符的重载

直接上代码

class Point
attr_accessor :x, :y

def initialize(x=0, y=0)
@x, @y = x, y
end

def inspect
"(#{x}, #{y})"
end

def +(other)
self.class.new(x + other.x, y + other.y)
end

def -(other)
self.class.new(x - other.x, y - other.y)
end

def -@
self.class.new(-x, -y)
end
end

p0 = Point.new(3, 6)
p1 = Point.new(1, 2)

p -p0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: