C# 如何将基参数从重载构造函数传递到派生类
主要 基类C# 如何将基参数从重载构造函数传递到派生类,c#,class,inheritance,C#,Class,Inheritance,主要 基类 static void Main(string[] args) { string name = "Me"; int height = 130; double weight = 65.5; BMI patient1 = new BMI(); BMI patient2 = new BMI(name,height,weight); Console.WriteLine(patient2.
static void Main(string[] args)
{
string name = "Me";
int height = 130;
double weight = 65.5;
BMI patient1 = new BMI();
BMI patient2 = new BMI(name,height,weight);
Console.WriteLine(patient2.Get_height.ToString() + Environment.NewLine + patient1.Get_height.ToString() );
Console.ReadLine();
}
派生类
class BMI
{
//memberVariables
private string newName;
private int newHeight;
private double newWeight;
//default constructor
public BMI(){}
//overloaded constructor
public BMI(string name, int height, double weight)
{
newName = name;
newHeight = height;
newWeight = weight;
}
//poperties
public string Get_Name
{
get { return newName; }
set { newName = value;}
}
public int Get_height
{
get { return newHeight; }
set { newHeight = value; }
}
public double Get_weight
{
get { return newWeight; }
set { newWeight = value; }
}
}
如何将基参数从BMI基类中的重载构造函数传递到派生类中?
每当我试图将它们传递到基参数时,都会得到无效的表达式错误。
或者我只需要将它们传递到一个健康对象中,并使用?
乙二醇
构造函数不是继承的,因此您需要为基类创建一个新的构造函数,但可以使用适当的参数调用基类构造函数:
class Health : BMI
{
private int newSize;
public Health(int Size, string Name, int Height, double Weight)
{
newSize = Size;
base.Get_Name = Name
base.Get_weight = Weight;
base.Get_height = Height;
}
}
像这样:
public Health(int size, string name, int height, double weight)
: base(name, height, weight)
{
newSize = size;
}
为什么不能调用传递参数的基类构造函数
class Health : BMI
{
private int newSize;
public Health(int Size, string Name, int Height, double Weight)
: base(Name, Height, Weight)
{
newSize = Size;
}
}
基本构造函数的大小写不正确。@d347hm4n谢谢,已修复。我建议您将属性重命名为仅
高度
、名称
、和重量
。在它们前面加上Get
使其看起来像是在调用方法或访问只读属性。
class Health : BMI
{
private int newSize;
public Health(int Size, string Name, int Height, double Weight)
: base(Name, Height, Weight)
{
newSize = Size;
}
}
public Health(int Size, string Name, int Height, double Weight)
: base(Name, Height, Weight)
{
newSize = Size;
}