我试图做继承程序如下:
class P1
end
class P2
end
class A < P1
end
class A < P2
end
Run Code Online (Sandbox Code Playgroud)
当我运行这个程序时,我收到如下错误:
superclass mismatch for class A (TypeError)
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个错误?
在定义类时,它默认继承Object.如果你把它作为任何其他类的子类,那么它将继承那个其他类.但是,只有在使用关键字class或方法首次定义自定义类时,才能执行此子类化Class::new.一旦你定义了它,当你第二次重新打开你的类时,就不会允许你改变它的超级类.
在你的例子中:
# here you are defining your new class A, so you can make it now a subclass of
# the parent class of any, like P1
class A < P1
end
# here you are reopeing the same class A. Now you are not again allowed to change the
# super class of it, which is P1.
class A < P2
end
Run Code Online (Sandbox Code Playgroud)
你可以做的是,make P1和P2模块,然后在你的程序过程中随时包含它们A.