上一小節的例子中,類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