英文:
Using super keyword
问题
这是代码:
class Point
def initialize(x, y)
@x = x
@y = y
end
end
class Point3D < Point
def initialize(x, y, z)
super
@z = z
end
end
这段代码有一个问题,即 Point3D
类的 initialize
方法调用 super
,但没有明确传递参数 x
和 y
。在 Ruby 中,如果你在子类的构造函数中使用 super
,它会自动传递与当前子类构造函数参数匹配的参数给父类的构造函数。但在这种情况下,Point
类的构造函数需要 x
和 y
参数,而 Point3D
类的构造函数接受 x
、y
和 z
参数。因此,需要显式传递这些参数给 super
,如下所示:
class Point
def initialize(x, y)
@x = x
@y = y
end
end
class Point3D < Point
def initialize(x, y, z)
super(x, y)
@z = z
end
end
这样修改后,代码应该能够正常工作,而不会出现 ArgumentError。
英文:
Can someone please explain to me why this code gives me an ArgumentError yet when using super without arguments ruby automatically passes the arguments that were inherited from the superclass or am I wrong
This is the code:
class Point
def initialize (x, y)
@x = x
@y = y
end
end
class Point3D < Point
def initialize (x, y, z)
super
@z = z
end
end
答案1
得分: 1
我认为你可以尝试以下的代码片段来解决你的问题:
class Point
def initialize(x, y)
@x = x
@y = y
end
end
class Point3D < Point
def initialize(x, y, z)
super(x, y) # 在这里传递参数
@z = z
end
end
简要总结一下,如果你在调用super
时不传递参数,参数会自动传递给超类的构造函数。
英文:
I think you can try the following code snippet for your problem:
class Point
def initialize(x, y)
@x = x
@y = y
end
end
class Point3D < Point
def initialize(x, y, z)
super(x, y) # Pass the arguments here
@z = z
end
end
As a quick summary, if you call super with no arguments, the arguments are automatically passed to the superclass's constructor then.
答案2
得分: 0
如果你看错误并使用你的假设,即当没有参数调用`super`时,它会将所有参数传递给其父类,你可以看到为什么它不起作用。
ArgumentError (参数数量错误(提供了3个,期望2个))
错误表示在某个地方传递了3个参数,而不是2个参数(`super`调用)。实际上,它会传递所有参数,而不仅仅是前几个参数,如果祖先方法接受较少的参数。这就像调用`Point.new(1,2,3)`,它会返回相同的错误。
在祖先方法接受不同数量的参数的情况下,你必须手动指定这些参数,因此以以下方式定义你的类初始化程序:
```ruby
class Point3D < Point
def initialize(x, y, z)
super(x,y)
@z = z
end
end
<details>
<summary>英文:</summary>
If you look at the error and use your assumption that when `super` is called without arguments it passes all arguments to its parent you can see why it does not work.
ArgumentError (wrong number of arguments (given 3, expected 2))
The error says you passed 3 instead of 2 arguments at some point (the `super` call). It actually passes ALL arguments, not just first few arguments if the ancestor method accepts less arguments. It is like calling `Point.new(1,2,3)` which would return the same error.
In a case where ancestor method accepts different number of arguments you have to specify these arguments manually and therefore define your class initializer this way:
```ruby
class Point3D < Point
def initialize(x, y, z)
super(x,y)
@z = z
end
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论