Welcome

首页 / 软件开发 / C# / 构造函数的参数

构造函数的参数2007-09-22 本站 上一小节的例子中,类A同时提供了不带参数和带参数的构造函数。

构造函数可以是不带参数的,这样对类的实例的初始化是固定的。有时,我们在对类进行实例化时,需要传递一定的数据,来对其中的各种数据初始化,使得初始化不再是一成不变的,这时,我们可以使用带参数的构造函数,来实现对类的不同实例的不同初始化。

在带有参数的构造函数中,类在实例化时必须传递参数,否则该构造函数不被执行。

让我们回顾一下10.2节中关于车辆的类的代码示例。我们在这里添加上构造函数,验证一下构造函数中参数的传递。

程序清单10-6:

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 weight of vehicle is:{0}",weight); }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 wheels 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:0
the weight of train is:0
the Passengers of train is:0
the wheel of car is:4
the weight of car is:2
the passengers of car is:4