2011-12-26 48 views
1

Ellipse类应该从我Shape类继承,但我收到此错误信息:重写属性不起作用

错误1“ConsoleApplication3.Ellipse”不实现继承的抽象成员“ConsoleApplication3.Shape.Perimeter .get'

我还收到了我隐藏的错误消息Area,属于Ellipse的属性。

任何人都可以帮助我吗?

我的形状类看起来是这样的:

public abstract class Shape 
{ 
    //Protected constructor 
    protected Shape(double length, double width) 
    { 
     _length = length; 
     _width = width; 
    } 


    private double _length; 
    private double _width; 

    public abstract double Area 
    { 
     get; 
    } 

我的椭圆形类是:

class Ellipse : Shape 
{ 
    //Constructor 
    public Ellipse(double length, double width) 
     :base(length, width) 
    { 

    } 

    //Egenskaper 
    public override double Area 
    { 
     get 
     { 
      return Math.PI * Length * Width; 
     } 
    } 
} 
+1

你能展示这两个类的代码吗? – 2011-12-26 22:36:59

+0

我把你的示例代码粘贴到控制台应用程序中,添加了长度和宽度的访问器,它编译得很好。比较你的示例代码和你的真实代码,你应该得到你的答案。 – 2011-12-26 22:51:15

回答

5

您需要使用override修改的面积和周长在Ellipse类,例如性能

public override double Area { get; } 

public override double Perimeter { get; } 

在Visual Studio中为你小费,把文字“形状”里面的光标(在椭圆形类),然后按Ctrl键+。这应该为未实现的成员添加存根

+0

我已经做到了,但它仍然无法正常工作。 public override double Area { get { return Math.PI * Length * Width; } } – 2011-12-26 22:41:43

1

可能是因为你没有声明长度,宽度在你的Ellipse类中的任何地方,所以你可能会遇到编译错误,为了编译你需要增强基类Shape的_length和_width属性的可见性。

public abstract class Shape 
{ 
    //Protected konstruktor 
    protected Shape(double length, double width) 
    { 
    _length = length; 
    _width = width; 
    } 

    // have these variables protected since you instantiate you child through the parent class.  

    protected double _length; 
    protected double _width; 

    public abstract double Area 
    { 
    get; 
    } 
} 
class Ellipse : Shape 
{ 
    //Konstruktor 
    public Ellipse(double length, double width) 
    : base(length, width) 
    { 

    } 

    //Egenskaper 
    public override double Area 
    { 
    get 
    { 
     // use the variable inherited since you only call the base class constructor. 
     return Math.PI * _length * _width; 
    } 
    } 
} 
+0

这是什么意思,“你还没有声明长度,宽度在你的Ellipse类中的什么地方”?你的答案看起来完全像我的解决方案 – 2011-12-26 23:05:13

+0

@HerrNilsson如果可以注意两件事1)保护double _length;并保护double _width; in Shape class – 2011-12-26 23:07:27

+0

2)public override double Area { get { return Math.PI * _length * _width; } } – 2011-12-26 23:07:43