日期:2014-05-18  浏览次数:20681 次

麻烦解释一下C#中的构造方法
C# code
 class Point
    {
        public double x, y;
        public Point()
        {
            this.x = 0;
            this.y = 0;
        }

        public Point(double x, double y)
        {
            this.x = x;
            this.y = y;
        }

        public  static double Distance(Point a, Point b)
        {
            double xdf = a.x - b.y;
            double ydf = a.y - b.y;
            return Math.Sqrt(xdf*xdf+ydf*ydf);
        }

请问一下上面这段代码里的是什么意思:
 public Point()
  {
  this.x = 0;
  this.y = 0;
  }

  public Point(double x, double y)
  {
  this.x = x;
  this.y = y;
  }
麻烦大家给我解释一下,我是初学.

------解决方案--------------------
new这个类的时候自动执行Point这个函数

至于执行那个,根据你new的时候的参数来顶

Point a = new Point() 就执行上面这个
Point a = new Point(1,2) 就执行下面这个

------解决方案--------------------
构造方法也是类里的方法,只不过比较特殊,
如果没有任何构造方法,系统会自动添加无参构造方法
如果程序员自己写了构造方法就按你写的方法进行初始化
构造方法用来形成实例。
你看到的是构造方法的重载,跟一般的方法重载一样,
如果不明白,你看看方法重载是怎么回事。
------解决方案--------------------
探讨
我是否可以这样理解?:

C# codepublic Point() //这个是无参方法
{
this.x = 0;
this.y = 0;
}

public Point(double x, double y) //这个是有参方法
{
this.x = x;
this.y = y;
}