永远不会分配c#字段,并且其默认值始终为null?

时间:2013-04-02 19:31:37

标签: c# class inheritance compiler-errors

C#Inhertance。我试图将类四边形继承到类sqaure。我无法弄清楚这一点,我得到了以下错误,我不知道这意味着什么。字段square.p1永远不会被赋值并且将始终具有其默认值null?

    using System;

    class testquadrilaterals 
    {
        static void Main() 
{
    quadrilateral obj1 = new quadrilateral(1.1, 1.2, 6.6, 2.8, 6.2, 9.9, 2.2, 7.4);
    obj1.printcoordinates();
    Console.WriteLine("\n");
    square obj2 = new square( 4.0, 0.0, 8.0, 0.0, 8.0, 4.0, 4.0, 4.0 );
    obj2.printsquare();

    Console.ReadLine();
}
    }

    class point 
    {
        private double x;
private double y;

public point(double x_coord, double y_coord)
{
    x = x_coord;
    y = y_coord;
}

public double X { get { return x; } set { x = value; } }
public double Y { get { return y; } set { y = value; } }

public override string ToString()
{
    return ("(" + X + ", " + Y + ")");
}
    }

    class quadrilateral
    {
point p1, p2, p3, p4;

public quadrilateral(double x1, double y1, double x2, double y2,
    double x3, double y3, double x4, double y4)
{
    p1 = new point(x1, y1);
    p2 = new point(x2, y2);
    p3 = new point(x3, y3);
    p4 = new point(x4, y4);
}

public point P1 { get { return p1; } set { p1 = value; } }
public point P2 { get { return p2; } set { p2 = value; } }
public point P3 { get { return p3; } set { p3 = value; } }
public point P4 { get { return p4; } set { p4 = value; } }

public void printcoordinates()
{
    Console.WriteLine("Coordinates of Quadrilateral: \n" + p1.ToString() + " " + p2.ToString() + " " + p3.ToString() + " " + p4.ToString() + " ");
}
    }


    class square : quadrilateral
    {
point p1, p2, p3, p4;

public square(double x1, double y1, double x2, double y2,
    double x3, double y3, double x4, double y4) : base (x1, y1, x2, y2, x3, y3, x4, y4)
{ }

public void printsquare()
{
    Console.WriteLine("Coordinates of Square: \n" + p1.ToString() + " " + p2.ToString() + " " + p3.ToString() + " " + p4.ToString() + " ");
    Console.WriteLine("Area: " + area());
   // Console.WriteLine("Sides: " + sides());
}

public double area() 
{

    return Math.Abs(p1.X - p2.X) * Math.Abs(p1.Y - p3.Y); 
}
// public double sides() { }

}

3 个答案:

答案 0 :(得分:2)

在这种情况下,类square定义了4个从未设置过的字段:p1,p2,p3和p4

class square : quadrilateral {
  point p1, p2, p3, p4;

  ...
}

这些字段是私有的,从不设置,因此它们本质上是无用的。 C#编译器会提醒您,因为这通常表示存在错误。

在这种情况下,您可能希望square只使用quadrilateral中的值。这些字段具有相同的名称和类型,并且这两种类型之间存在继承关系。如果是这种情况,您应该删除square中的字段,并将protected中的quadrilateral的辅助功能更改为

class quadrilateral {
  protected  point p1, p2, p3, p4;
  ...
}

这将允许square访问值

答案 1 :(得分:0)

如果从四面体继承,则不需要在square中再次定义变量p1 / p2 / p3 / p4,您将从基类继承它们。

答案 2 :(得分:0)

在Square :: area()中,p1s和p2s指的是方形类中定义的那些,而不是四边形类中的那些。你有square :: p1,square :: p2等和quadrilateral :: p1,quadrilateral :: p2等。方形p1s和p2s永远不会分配给。要让你的方形类使用四边形类'p1s和p2s,不要在正方形中重新定义它们。