C#入门之重载

重载 
using System;
class Vector
{
 private double XVector;
 private double YVector;
 //构造函数
 public Vector(double x, double y )
 {
  XVector = x;
  YVector = y;
 }
 //获取向量的长度
 public double GetLength( )
 {
  double Length = Math.Sqrt( XVector*XVector + YVector*YVector );
  return Length;
 }
 //重载运算符==
 public static bool operator == ( Vector a, Vector b )
 {
  return ( (a.XVector == b.XVector) && (a.YVector == b.YVector) );
 }
 //重载运算符!=
 public static bool operator != ( Vector a, Vector b )
 {
  return !( a == b );
 }
 //重载运算符>:以向量长度判断是否为真
 public static bool operator > ( Vector a, Vector b )
 {
  return a.GetLength( ) > b.GetLength( );
 }
 //重载运算符<
 public static bool operator < ( Vector a, Vector b )
 {
  return a.GetLength( ) < b.GetLength( );
 }
 //重载运算符>=
 public static bool operator >= ( Vector a, Vector b )
 {
  return ( a == b ) || ( a > b );
 }
 //重载运算符<=
 public static bool operator <= ( Vector a, Vector b )
 {
  return ( a == b ) || ( a < b );
 }
}

class Test
{
 static public void Main( )
 {
  Vector vector1 = new Vector( 3, 4 );
  Vector vector2 = new Vector( 0, 5 );
  Vector vector3 = new Vector( 2, 2 );
  Console.WriteLine("向量1为( 3, 4 ) /t 向量2为( 0, 5 ) /t 向量3为( 2, 2 )");
  Console.WriteLine("向量1 == 向量2 为:{0}", vector1 == vector2 );
  Console.WriteLine("向量1 != 向量2 为:{0}", vector1 != vector2 );
  Console.WriteLine("向量1 >  向量3 为:{0}", vector1 > vector3 );
  Console.WriteLine("向量2 <  向量3 为:{0}", vector2 < vector3 );
  Console.WriteLine("向量1 >= 向量2 为:{0}", vector1 != vector2 );
  Console.WriteLine("向量1 <= 向量2 为:{0}", vector1 != vector2 );
 }
}

虚方法的声明和使用
using System;
public class Graph
{
 protected double ParaVal;
 protected double pi = 3.1415926;
 public Graph ( double Para )
 {
  ParaVal = Para;
 }
 //定义虚方法:求面积
 public virtual double Area( )
 {
  return ParaVal;
 }
}
//图形的子类正方形
public class Square : Graph
{
 public Square( double Para ) : base ( Para )
 {
 }
 //重载正方形求面积的方法
 public override double Area( )
 {
  return ParaVal * ParaVal;
 }
}
//图形的子类等边三角形
public class EqTriangle : Graph
{
 public EqTriangle( double Para ) : base ( Para )
 {
 }
 //重载等边三角形求面积的方法
 public override double Area()
 {
  return ParaVal * ParaVal * Math.Sin( pi/3 ) / 2;
 }
}
//图形的子类圆
public class Circle : Graph
{
 public Circle( double Para ) : base( Para )
 {
 }
 //重载圆求面积的方法
 public override double Area( )
 {
  return  pi * ParaVal * ParaVal;
 }
}

class Test 
{
 public static void Main( )
 {
  double Length = 6;
  
  Graph Init = new Graph( Length );
  Graph Squa = new Square( Length );
  Graph Tria = new EqTriangle( Length );
  Graph Circ = new Circle( Length );

  Console.WriteLine("原始图形的面积是:/t{0}", Init.Area());
  Console.WriteLine("正方形的面积是:/t{0}", Squa.Area());
  Console.WriteLine("等边三角形的面积是:/t{0}", Tria.Area());
  Console.WriteLine("圆形的面积是:  /t{0}", Circ.Area());
 }
}

posted on 2012-03-16 09:54  zhangtao1212  阅读(353)  评论(0编辑  收藏  举报

导航