读书人

[急]一个关于构造函数传参的有关问题

发布时间: 2012-03-25 20:55:17 作者: rapoo

[急,在线等]一个关于构造函数传参的问题
using System;
class Vehicle
{
public int wheels;
protected float weight;
public Vehicle(){;}
public Vehicle(int w,float g){
wheels = w;
weight = g;
}
public void Show(){
Console.WriteLine( "the wheel of vehicle is :{0} ",wheels);
Console.WriteLine( "the wheel of vehicle is :{0} ",wheels);
}
};
class train
{
public int num;
private int passengers;
private float weight;
public Train(){;}
public Train(int n,int p,float w){
num = n;
passengers = p;
weight = w;
}
public void Show(){
Console.WriteLine( "the num of train is :{0} ",num);
Console.WriteLine( "the weight of train is:{0} ",weight);
Console.WriteLine( "the passengers train car is:{0} ",passengers);
}
}
class Car:Vehicle
{
int passengers;
public Car(int w,float g,int p):base(w,g)
{
wheels = w;
weight = g;
passengers = p;
}
new public void Show()
{
Console.WriteLine( "the wheel of car is:{0} ",wheels);
Console.WriteLine( "the weight of car is:{0} ",weight);
Console.WriteLine( "the Passengers of car is:{0} ",passengers);
}
}
class Test
{
public static void Main()
{
Vehicle v1 = new Vehicle(4,5);


Train t1 = new Train();
Train t2 = new Train(10,100,100);
Car c1 = new Car(4,2,4);
v1.Show();
t1.Show();
t2.Show();
c1.Show();
}
}
程序的运行结果为:
the wheel of vehicle is: 0
the weight of vehicle is: 0
the num of train is: 0
the weight of train is: 0
the passengers of train is: 0
the num of train is: 10
the weight of train is: 100
the passengers of train is: 100
the wheel of car is: 4
the weight of car is: 2
the passengers of car is: 4
以上我是从一本书上抄下来的,我机器没有IDE,全手敲的,可能有问题,不要执行,我的问题是:
1。 为什么前两个结果是0? 我感觉是4和5
2。 为什么在构造函数后面强些base()?就算些我也觉得应该是base(w,g,p)为什么是base(w,g)呢?难道调用的是父类的base()?
在线等,希望各位大侠迅速给答案,当然也有可能书印刷有问题。呵呵。

[解决办法]
1.
前两个结果是 4,4
因为你输出的都是 wheels (估计手误)
Console.WriteLine( "the wheel of vehicle is :{0} ",wheels);
Console.WriteLine( "the wheel of vehicle is :{0} ",wheels);

2.
在子类的构造函数后面跟base(),base(w,g,p),base(w,g)都可以,它代表子类的构造函数可以选择父类的构造函数
[解决办法]
第一个问题 我 没 运行 个人感觉好像 是 4 5 啊?
(不算你代码输入错误:
Console.WriteLine( "the wheel of vehicle is :{0} ",wheels);
Console.WriteLine( "the wheel of vehicle is :{0} ",wheels);
)

第二个 base (w,g) 指的是 调用父类的 带参构造函数吧 ?

你的 基础MS比我烂些
[解决办法]
第一按照你帖的代码答案是4,4 因为答应的是同一个变量..
第二base应该就是父类的

读书人网 >C#

热点推荐