基类不包含无参数构造函数?
我通过删除一些空的构造函数来使我的构造函数更加严格。我对继承还很陌生,并且对我得到的错误感到困惑:基类不包含无参数构造函数。如何让 A2 继承 A 而 A 中没有空构造函数。另外,根据我个人的理解,为什么 A2 需要 A 的空构造函数?
Class A{
//No empty constructor for A
//Blah blah blah...
}
Class A2 : A{
//The error appears here
}
I'm making my constructors a bit more strict by removing some of my empty constructors. I'm pretty new to inheritance, and was perplexed with the error that I got: Base Class Doesn't Contain Parameterless Constructor. How can I make A2 inherit from A without there being an empty constructor in A. Also, for my own personal understanding, why is A2 requiring an empty constructor for A?
Class A{
//No empty constructor for A
//Blah blah blah...
}
Class A2 : A{
//The error appears here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在类 A2 中,您需要确保所有构造函数都使用参数调用基类构造函数。
否则,编译器将假定您要使用无参数基类构造函数来构造 A2 对象所基于的 A 对象。
例子:
In class A2, you need to make sure that all your constructors call the base class constructor with parameters.
Otherwise, the compiler will assume you want to use the parameterless base class constructor to construct the A object on which your A2 object is based.
Example:
例子:
Example:
如果您的基类没有无参数构造函数,则需要使用
base
关键字从派生类中调用无参数构造函数:If your base class doesn't have a parameterless constructor, you need to call one from your derived class using
base
keyword:它必须调用一些构造函数。默认是调用
base()
。您还可以在对
base()
的调用中使用当前构造函数的静态方法、文字和任何参数。It has to call some constructor. The default is a call to
base()
.You can also use static methods, literals, and any parameters to the current constructor in calls to
base()
.因为如果 A 没有默认构造函数,则 A2 的构造函数需要使用 A 的构造函数的参数调用 base()。请参阅此问题:在 C# 中调用基本构造函数
Because if A has no default constructor then the constructor of A2 needs to call base() with the arguments to the constructor of A. See this question: Calling the base constructor in C#
当您创建派生类的对象时,您的基类构造函数会自动被调用。因此,在您创建派生类对象时,并且您的派生类对象没有构造函数接受一个或多个参数,因此将没有任何内容可以传递给需要一个参数的基类构造函数。
为此,您需要将一些内容传递给基类构造函数,如下所示:
when you create the object of your derived class,your base class constructor gets called automatically.So at the time you create your derived class object,and your derived class object has not constructor taking one or more arguments, there will be nothing to pass to the base class constructor that wants one argument.
so to do that, you need to pass something to the base class constructor as follows: