继承带参数的基类构造函数
简单代码:
class foo
{
private int a;
private int b;
public foo(int x, int y)
{
a = x;
b = y;
}
}
class bar : foo
{
private int c;
public bar(int a, int b) => c = a * b;
}
Visual Studio 抱怨 bar
构造函数:
错误 CS7036 没有给出与
foo.foo(int, int)
所需的形式参数x
相对应的参数。
什么?
Simple code:
class foo
{
private int a;
private int b;
public foo(int x, int y)
{
a = x;
b = y;
}
}
class bar : foo
{
private int c;
public bar(int a, int b) => c = a * b;
}
Visual Studio complains about the bar
constructor:
Error CS7036 There is no argument given that corresponds to the required formal parameter
x
offoo.foo(int, int)
.
What?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是基类 foo 没有无参数构造函数。因此,您必须使用派生类构造函数的参数调用基类的构造函数:
The problem is that the base class
foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:我可能是错的,但我相信既然你是从 foo 继承的,你必须调用一个基本构造函数。由于您显式地将 foo 构造函数定义为 require (int, int) ,现在您需要将其传递到链上。
这将首先初始化 foo 的变量,然后您可以在 bar 中使用它们。另外,为了避免混淆,我建议不要将参数命名为与实例变量完全相同。尝试使用 p_a 或其他东西,这样您就不会意外地处理错误的变量。
I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.
This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.