8.7.8 Instance constructors

来源:互联网 发布:马拉多纳 知乎 编辑:程序博客网 时间:2024/05/19 14:39
An instance constructor is a member that implements the actions required to
initialize an instance of a class.
The example
using System;
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 xdiff = a.x - b.x;
double ydiff = a.y - b.y;
return Math.Sqrt(xdiff * xdiff + ydiff * ydiff);
}
public override string ToString() {
return string.Format("({0}, {1})", x, y);
}
}
class Test
{
static void Main() {
Point a = new Point();
Point b = new Point(3, 4);
double d = Point.Distance(a, b);
Console.WriteLine("Distance from {0} to {1} is {2}", a, b, d);
}
}
shows a Point class that provides two public instance constructors, one of
which takes no arguments, while
the other takes two double arguments.
If no instance constructor is supplied for a class, then an empty one with
no parameters is automatically
provided.
原创粉丝点击