我做了以下例子来演示。如果我name
在课堂上都使用Song
,KarokeSong
我会得到一个错误。
class Song
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
def to_s
"Song: #{@name}--#{@artist} (#{@duration})"
end
end
class KarokeSong < Song
def initalize(name, kname, artist, duration, lyrics)
super(name, artist, duration)
@name = kname
@lyrics = lyrics
end
def to_s
"KS: #{@name}--#{@artist} (#{@duration}) [#{@lyrics}] **#{@name}**"
end
end
songA = Song.new("Bicyclops", "Fleck", 260)
puts songA.to_s
songB = KarokeSong.new("John", "Casey", "The Band", 400, "And now, the...")
puts songB.to_s
这是我在尝试运行文件时收到的错误。
stanley@ubuntu:~/Github/webdev_class/ruby$ ruby inheritance.rb
Song: Bicyclops--Fleck (260)
inheritance.rb:28:in `initialize': wrong number of arguments(5 for 3) (ArgumentError)
from inheritance.rb:28:in `new'
from inheritance.rb:28:in `<main>'
我猜name
如果存在继承关系,则不允许使用该名称两次。我不确定这是否与 Ruby 不支持多重继承或 V 指针这一事实有关。提前感谢您对正在发生的事情的建议。