虚函数简单地说,那些被virtual关键字修饰的成员函数。虚函数的作用,用专业术语来解释就是实现多态性(Polymorphism),多态性就是实现共同的方法,但因个体差异而采用不同的策略。
简单的示例
public
class
ShapeWithArea
... {
protected double x,y,area;
protected string name;
public ShapeWithArea(double x,double y)
...{
this.x=x;
this.y=y;
}
public virtual double Area()
...{
area= x*y;
return area;
}
public override string ToString()
...{
return name+"的面积是:"+Area().ToString();
}
}
public class Circle:ShapeWithArea
... {
public Circle(int r):base(r,0)
...{
base.name="圆";
}
public override double Area()
...{
return Math.PI*x*x;
}
}
public class Sphere:ShapeWithArea
... {
public Sphere(int r):base(r,0)
...{
base.name="球";
}
public override double Area()
...{
return 4*Math.PI*x*x;
}
}
public class Cylinder:ShapeWithArea
... {
public Cylinder(int r,int h):base(r,h)
...{
base.name="圆柱";
}
public override double Area()
...{
return 2*Math.PI*x*x+2*Math.PI*x*y;
}
}
... {
protected double x,y,area;
protected string name;
public ShapeWithArea(double x,double y)
...{
this.x=x;
this.y=y;
}
public virtual double Area()
...{
area= x*y;
return area;
}
public override string ToString()
...{
return name+"的面积是:"+Area().ToString();
}
}
public class Circle:ShapeWithArea
... {
public Circle(int r):base(r,0)
...{
base.name="圆";
}
public override double Area()
...{
return Math.PI*x*x;
}
}
public class Sphere:ShapeWithArea
... {
public Sphere(int r):base(r,0)
...{
base.name="球";
}
public override double Area()
...{
return 4*Math.PI*x*x;
}
}
public class Cylinder:ShapeWithArea
... {
public Cylinder(int r,int h):base(r,h)
...{
base.name="圆柱";
}
public override double Area()
...{
return 2*Math.PI*x*x+2*Math.PI*x*y;
}
}
//
如何调用
txtinfo.Text = string .Empty;
ShapeWithArea[] test = new ShapeWithArea[ 3 ];
test[ 0 ] = new Circle(Int32.Parse(txtcircle.Text));
test[ 1 ] = new Sphere(Int32.Parse(txtsphere.Text));
test[ 2 ] = new Cylinder(Int32.Parse(txtcylinderr.Text),Int32.Parse(txtcylinderh.Text));
string info = string .Empty;
foreach (ShapeWithArea swa in test)
... {
info+=swa.ToString();
}
txtinfo.Text = info;
txtinfo.Text = string .Empty;
ShapeWithArea[] test = new ShapeWithArea[ 3 ];
test[ 0 ] = new Circle(Int32.Parse(txtcircle.Text));
test[ 1 ] = new Sphere(Int32.Parse(txtsphere.Text));
test[ 2 ] = new Cylinder(Int32.Parse(txtcylinderr.Text),Int32.Parse(txtcylinderh.Text));
string info = string .Empty;
foreach (ShapeWithArea swa in test)
... {
info+=swa.ToString();
}
txtinfo.Text = info;
http://dl2.csdn.net/down4/20070715/15115143803.rar
示例工程文件