如果派生类没有参数化构造函数,我该如何从派生类调用基类的参数化构造函数?

4

我有一个基类,其中包含两个构造函数:默认构造函数和参数化构造函数。另一个类继承自该基类,并且只有一个默认构造函数。如何从派生类调用基类的参数化构造函数?

3个回答

8

不太清楚您的问题是什么,但我猜测您想要在子类中添加一个明确的无参构造函数:

// Parameterless child constructor calling parameterized base constructor
public Child() : base("foo", "bar") {
}

或者同时添加有参数和无参数的函数:
public Child() {
}

public Child(string foo, string bar) : base(foo, bar) {
}

请注意,构造函数不会被继承 - 所以仅因为基类有特定的构造函数签名,并不意味着可以使用该签名实例化类。子类必须自己提供它。
任何由编译器提供的无参构造函数将始终调用其基类的无参构造函数。

2
像这样的内容吗?
class Parent
{
    public Parent(){}
    public Parent(string s) {}
}

class Child : Parent
{
    public Child() : base("42") { }
}

1

给你:

// 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   
        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接