本帖最后由 许庭洲 于 2014-7-29 15:36 编辑
using System;
class Vehicle//定义汽车类
{
public int wheels;//公有成员:轮子个数
protected float weight;//保护成员:重量
public Vehicle(int w,float g)
{
wheels=w;
weight = g;
}
public virtual void Speak()
//基类虚方法的重载是函数重载的另一种特殊形式。在派生类中重新定义此虚函数,
//要求的是方法名称,返回值类型,参数表中的参数,类型,顺序都必须与基类中的虚函数完全一致。
{
Console.WriteLine("The vehicle is speaking!");
}
};
class Car:Vehicle//定义轿车类
{
//类中两个以上的方法(包括隐藏而来的方法),取得名字相同,
//只要使用的参数类型或者参数个数不同,编译器知道在何种情况下因该调用哪个方法。
int passengers;//私有成员:乘客数
public Car(int w,float g,int p):base(w,g)
{
wheels=w;
weight=g;
passengers=p;
}
public override void Speak()
//在派生类中声明对虚方法的重载,要求在声明中加上override关键字,
//而不能有new,static或virtual修饰符。
{
Console.WriteLine("("The car is speaking: Di-di!");
}
}
class Truck:Vehicle//定义卡车类
{
int passengers;//私有成员:乘客数
float load;//私有成员:载重量
public Truck(int w,float g,int p,float l):base(w,g)
{
wheels =w;
weight=g;
passengers=p;
load=1;
}
public override void Speak()
{
Console.WriteLine("The truck is speaking:Ba-ba!"):
}
}
class Test
{
Vehicle v1=new Vehicle ();
Car c1=new Car(4,2,5);
Truck t1 =new Truck(6,5,3,10);
v1.Speak();
v1=c1;
v1.Speak();
c1.Speak();
v1=t1;
v1.Speak();
t1.Speak();
}
}
//--------------------------------------------程序结果----------------------------------------------//
The Vehicle is speaking!
The car is speaking: Di-di!
The car is speaking: Di-di!
The truck is speaking: Ba-ba!
The truck is speaking:Ba-ba!
//--------------------------------------------程序结果----------------------------------------------//
|