C#设有一个描述坐标点的CPoint类,其私有成员变量x、y代表一个点的x、y坐标值。编写程序
默认值可以用构造方法的重载来实现,也可直接设置。
⑴用构造方法的重载版本:
using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
CPoint cp=new CPoint();
cp.Display();
cp.SetPoint(80,150);
cp.Display();
Console.ReadLine();
}
}
public class CPoint
{
private int x;
private int y;
public CPoint():this(60,75)
{
}
public CPoint(int x,int y)
{
this.x=x;
this.y=y;
}
public void Display()
{
Console.WriteLine("x={0},y={1}",x,y);
}
public void SetPoint(int x,int y)
{
this.x=x;
this.y=y;
}
}
⑵直接设置默认值的版本:
using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
CPoint cp=new CPoint();
cp.Display();
cp.SetPoint(80,150);
cp.Display();
Console.ReadLine();
}
}
public class CPoint
{
private int x=60;
private int y=75;
public CPoint()//这回不需要了:this(60,75)
{
}
public CPoint(int x,int y)
{
this.x=x;
this.y=y;
}
public void Display()
{
Console.WriteLine("x={0},y={1}",x,y);
}
public void SetPoint(int x,int y)
{
this.x=x;
this.y=y;
}
}
运行结果: