我通过删除一些空的构造函数来使我的构造函数更加严格。我对继承还很陌生,并且对我得到的错误感到困惑:基类不包含无参数构造函数。如何让 A2 继承 A 而 A 中没有空构造函数。另外,根据我个人的理解,为什么 A2 需要 A 的空构造函数?
Class A{
//No empty constructor for A
//Blah blah blah...
}
Class A2 : A{
//The error appears here
}
在类 A2 中,您需要确保所有构造函数都使用参数调用基类构造函数。
否则,编译器将假定您要使用无参数基类构造函数来构造 A2 对象所基于的 A 对象。
Example:
class A
{
public A(int x, int y)
{
// do something
}
}
class A2 : A
{
public A2() : base(1, 5)
{
// do something
}
public A2(int x, int y) : base(x, y)
{
// do something
}
// This would not compile:
public A2(int x, int y)
{
// the compiler will look for a constructor A(), which doesn't exist
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)