ruby – 如何创建一个构造函数看起来像内置类的构造函数的类?
发布时间:2020-12-17 03:41:47 所属栏目:百科 来源:网络整理
导读:Complex是一个内置类.为了制作一个复杂的对象,我写道: Complex(10,5) 但是,如果我创建自己的类Thing: class Thing def initalize() endend 要创造一个新的东西,我必须写: Thing.new(...) 是否有可能为Thing创建一个构造函数,所以我可以写: Thing(...) 并
Complex是一个内置类.为了制作一个复杂的对象,我写道:
Complex(10,5) 但是,如果我创建自己的类Thing: class Thing def initalize() end end 要创造一个新的东西,我必须写: Thing.new(...) 是否有可能为Thing创建一个构造函数,所以我可以写: Thing(...) 并使它像一个内置的类,如Complex(1,1)? 解决方法class Dog def initialize(name) @name = name end def greet puts 'hello' end end def Dog(x) Dog.new(x) #Create a new instance of the Dog class and return it. end d = Dog("Rover") d.greet --output:-- hello (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |