子类中的方法如何读取基类中的构造函数里的值?~~~
。。。可能标题看起来有点抽象。。。但是那的确是我所想的。。这倒奇怪的题的完整题目是:
定义一个正方形类,包含左上角的坐标(x,y)、边长字段(bianchang)。并为所有字段添加可读和可写的属性。添加一个无参数的构造函数,坐标默认为0,0,边长也为0,添加一个带坐标参数的构造函数,边长为0,添加一个带坐标和边长参数的构造函数;添加一方法返回其坐标,添加一方法返回周长,添加一方法返回面积。最后在主方法中用自己定义的三个构造函数实例化三个正方形并输出其坐标、周长和面积。
目前正在纠结如何利用 自己定义的三个构造函数实例化三个正方形并输出其坐标、周长和面积。。。。
[解决办法]
class Program
{
static void Main(string[] args)
{
正方形 zfx1 = new 正方形();
正方形 zfx2 = new 正方形(10, 20);
正方形 zfx3 = new 正方形(11, 21, 4);
Console.WriteLine("正方形1,坐标:{0},周长:{1},面积:{2}", zfx1.Method1(), zfx1.Method2().ToString(), zfx1.Method3().ToString());
Console.WriteLine("正方形2,坐标:{0},周长:{1},面积:{2}", zfx2.Method1(), zfx2.Method2().ToString(), zfx2.Method3().ToString());
Console.WriteLine("正方形3,坐标:{0},周长:{1},面积:{2}", zfx3.Method1(), zfx3.Method2().ToString(), zfx3.Method3().ToString());
Console.ReadKey();
}
}
class 正方形
{
private int x;
private int y;
private int bianchang;
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
public int Bianchang
{
get { return bianchang; }
set { bianchang = value; }
}
public 正方形()
{
this.X = 0;
this.Y = 0;
this.Bianchang = 0;
}
public 正方形(int x, int y)
{
this.X = x;
this.Y = y;
this.Bianchang = 0;
}
public 正方形(int x, int y,int bianchang)
{
this.X = x;
this.Y = y;
this.Bianchang = bianchang;
}
public string Method1()
{
return this.X + "," + this.Y;
}
public int Method2()
{
return this.Bianchang * 4;
}
public int Method3()
{
return this.Bianchang * Bianchang;
}