派生类(把问题分解)

问题:、

【实验内容】
1.把定义平面直角坐标系上的一个点的类CPoint作为基类,派生出描述一条直线的类Cline,再派生出一个矩形类CRect。要求成员函数能求出两点间的距离、矩形的周长和面积等。设计一个测试程序,并构造完整的程序。
提示:
(1)可能用到的函数:math类中的函数。
(2)注意数据类型的转换。


代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            CPoint p1 = new CPoint(3, 3); 
            CPoint p2 = new CPoint(6, 6); 
            CPoint p3 = new CPoint(4, 6); 
            CPoint p4 = new CPoint(4, 9);//定义4个点

            Cline L = new Cline();
            int line1 = (int)L.GetLine(p1, p2);//强制转换成整型
            int line2 = (int)L.GetLine(p3, p4);//两个两个点得到两条直线
            
            CRect a = new CRect();
            int area =a.GetArea(line1, line2) ;
            int zhouchang =a.GetZhouchang(line1, line2);

            Console.WriteLine("p1和p2,p3和p4组成的线段L1和L2分别是{0}和{1}\n", line1, line2);
            Console.WriteLine("用L1和L2组成的矩形的面积和周长分别是{0}和{1}\n", area,zhouchang);
            Console.ReadKey();
        }
    }
   public  class CPoint//描述点
    {
        public CPoint()
        {
        }
        public  int x, y;
        public CPoint(int x, int y)
        {
            this.x = x;
            this.y = y;
            Console.WriteLine("初始化的点为({0},{1})\n", x, y);
        }
    }
    public class Cline : CPoint//描述直线
    {
        public Cline()
        {
        }
         public  double GetLine(CPoint p1, CPoint p2)//较为简便,不用输入四个值
        {
          double heng=Math.Pow(p1.x-p2.x,2);
          double zong=Math.Pow(p1.y-p2.y,2);
          double result = Math.Sqrt(heng + zong);
          return result;
        }
    }
    public class CRect : Cline//描述矩形
    {
        public int  GetZhouchang(int h, int w)
        {
            int c = (h + w) * 2;
            return c;
        }
        public  int GetArea(int h, int w)
        {
            int s = h*w;
            return s;
        }  
    }


}

你可能感兴趣的:(c#)