错误:父类不包含带0参数的构造函数

时间:2013-04-03 16:20:44

标签: c#

最初我收到一个错误,我不能在咖啡类“Coffee”中将“_coffee”命名为“_coffee”,因为成员名称不能与其封闭类型相同。当我将名称更改为_coffee时,我收到一条错误“coffeeShop不包含带0参数的构造函数。”我在网上找到了解决方案,但它们似乎不适用于我的应用程序或正常工作。请帮忙。

public class coffeeShop
{
    string _size;
    string _type;
    public coffeeShop(string size, string type)
    {
        _size = size;
        _type = type;
                }
    public override string ToString()
    {
        return String.Format("Thanks for ordering: {0}, {1}", _size, _type);
    }
}
class Coffee : coffeeShop
{
    string _size;
    string _type;
    string _caffiene;
    public virtual void _Coffee( string size, string type, string caffiene)
{
    _caffiene = caffiene;
    _size = size;
    _type = type;
}
    public override string ToString()
    {
        return String.Format("Product Information for: {0} {1} {3}", _size, _type, _caffiene);
    }
}

2 个答案:

答案 0 :(得分:5)

如果未在类型中定义构造函数,则C#编译器会发出默认(无参数)构造函数。这就是它试图为你的Coffee类做的事情(默认情况下是在基类中寻找一个无参数的构造函数来调用),但是你的基类(coffeeShop)只有一个接受2个参数的构造函数。

因此,任何子类都需要通过base关键字显式调用此构造函数:

public Coffee(string size, string type, string caffiene) : base(size, type)
{
  _caffiene = caffiene;
}

答案 1 :(得分:2)

更改

public virtual void _Coffee( string size, string type, string caffiene)
{
    _caffiene = caffiene;
    _size = size;
    _type = type;
}

public Coffee(string size, string type, string caffiene)
   : base(size, type)
{
    _caffiene = caffiene;
    _size = size;
    _type = type;
}

或者另外添加

public coffeeShop()
{
}

将在基类

中定义无参数构造函数

请注意,您要重新声明大小和类型,将构造函数更改为

会更有意义
public Coffee(string size, string type, string caffiene)
   : base(size, type)
{
    _caffiene = caffiene;
}

_size类中删除_typeCoffee,并在基类(protected)中将它们声明为coffeeShop