[英]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.