[英]abstract class with more then one parameterized constructor and derived class with parameterized constructor
[英]How can I call a base class's parameterized constructor from a derived class if the derived class has no parameterized constructor?
我有一个带有两个构造函数的基类:默认构造函数和参数化构造函数。 另一个类继承自该基类,它只有一个默认的构造函数。 如何从派生类中调用基类的参数化构造函数?
目前还不完全清楚你的问题是什么,但我怀疑你要么在你的子类中添加一个显式的无参数构造函数:
// Parameterless child constructor calling parameterized base constructor
public Child() : base("foo", "bar") {
}
或者添加参数化和无参数的:
public Child() {
}
public Child(string foo, string bar) : base(foo, bar) {
}
请注意,构造函数不是继承的 - 因为基类具有特定的构造函数签名并不意味着您可以使用该签名实例化类。 儿童班必须自己提供。
任何编译器提供的无参数构造函数将始终调用其基类的无参数构造函数。
像这样的东西?
class Parent
{
public Parent(){}
public Parent(string s) {}
}
class Child : Parent
{
public Child() : base("42") { }
}
干得好:
// Parent class
class Parent
{
public Parent()
{
// Paremeterless constructor
}
public Parent(string a, int b)
{
// Paremterised constructor
}
}
// Child class
class Child : Parent
{
public Child()
:base("hi", 10)
{
// Parameterized constructor of the base class is invoked
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.