8.7.8 Instance constructors

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航