带参数的基本 class 构造函数的继承
Inheritance with base class constructor with parameters
简单代码:
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
构造函数:
Error CS7036 There is no argument given that corresponds to the required formal parameter x
of foo.foo(int, int)
.
什么?
问题是基础 class foo
没有无参数构造函数。因此,您必须使用派生 class:
的构造函数中的参数调用基础 class 的构造函数
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
我可能是错的,但我相信既然你是从 foo 继承的,你必须调用一个基础构造函数。由于您明确定义了 foo 构造函数以要求 (int, int) 现在您需要将其向上传递。
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
这将首先初始化foo 的变量,然后您就可以在bar 中使用它们了。此外,为避免混淆,我建议不要将参数命名为与实例变量完全相同的名称。试试 p_a 之类的东西,这样你就不会不小心处理了错误的变量。
简单代码:
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
构造函数:
Error CS7036 There is no argument given that corresponds to the required formal parameter
x
offoo.foo(int, int)
.
什么?
问题是基础 class foo
没有无参数构造函数。因此,您必须使用派生 class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
我可能是错的,但我相信既然你是从 foo 继承的,你必须调用一个基础构造函数。由于您明确定义了 foo 构造函数以要求 (int, int) 现在您需要将其向上传递。
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
这将首先初始化foo 的变量,然后您就可以在bar 中使用它们了。此外,为避免混淆,我建议不要将参数命名为与实例变量完全相同的名称。试试 p_a 之类的东西,这样你就不会不小心处理了错误的变量。