【发布时间】:2012-10-26 22:28:35
【问题描述】:
在我的表单加载时,我有这个代码:
private void Form1_Load(object sender, EventArgs e)
{
CharityCyclists cyclist1 = new CharityCyclists();
CharityCyclists cyclist2 = new CharityCyclists("a", 1, "Finished", 0, 0, 0, "One Wheel", 1, 500);
cyclist1.Type = "Novelty Charity Cyclist";
cyclist1.Number = 1;
cyclist1.Finished = "Not Finished";
cyclist1.Hours = 0;
cyclist1.Mins = 0;
cyclist1.Secs = 0;
cyclist1.Bicycle = "Tricycle";
cyclist1.Wheels = 3;
cyclist1.FundsRaised = 300;
}
但是,我收到一条错误消息,提示“'CycleEvent.CharityCyclists' 不包含采用 0 个参数的构造函数”,它表示该错误与这部分代码有关:
CharityCyclists cyclist1 = new CharityCyclists();
这是我的 CharityCyclists 课程:
class CharityCyclists : Cyclists
{
private string bicycle;
private int wheels;
private double fundsRaised;
public string Bicycle
{
get { return bicycle; }
set { bicycle = value; }
}
public int Wheels
{
get { return wheels; }
set { wheels = value; }
}
public double FundsRaised
{
get { return fundsRaised; }
set { fundsRaised = value; }
}
public CharityCyclists(String type, int number, String finished, int hours, int mins, int secs, string bicycle, int wheels, double fundsRaised) : base(type, number, finished, hours, mins, secs, fundsRaised)
{
this.bicycle = bicycle;
this.wheels = wheels;
this.FundsRaised = fundsRaised;
}
public override string ToString()
{
return base.ToString() + " riding a " + bicycle + " with " + wheels + " wheels" ;
}
}
谢谢!
【问题讨论】:
-
错误的哪一部分你不明白?
-
因为你没有像
public CharityCyclists(){}这样的构造函数 -
我认为海报来自 C++ 背景,编译器将在其中生成默认 c'tor。下面的答案将解释 C# 不会生成默认构造函数。
-
@DonalLafferty:在相同情况下,C++ 也不会创建默认 ctor。在此 C++ 和 C#(和 Java)表现相同。一旦显式创建了构造函数,它将不再生成“默认”构造函数。
标签: c# constructor arguments