使用带参数的基类构造函数继承 [英] 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;
}
}
$ b
Visual Studio complains about the "bar" constructor:
错误CS7036没有参数对应于'foo.foo(int,int)'所需的形式参数'x'。
Error CS7036 There is no argument given that corresponds to the required formal parameter 'x' of 'foo.foo(int, int)'.
什么??
推荐答案
问题是基类 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:
public bar(int a, int b)
: base(a, b)
{
c = a * b;
}
这篇关于使用带参数的基类构造函数继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文