2011-12-26 43 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