开发者

inheritance - exercise

Alri开发者_如何学Cght, so I'm currently learning inheritance, and I've done something, this is the code:

class array
{
    int [] arr;
    public array(int[] arr)
    {
        this.arr = arr;
    }
    public int Biggest()
    {
        return arr.Max();
    }
    public int Min()
    {
        return arr.Min();
    }
    public int SumArr()
    {
        return arr.Sum();
    }
}
class array2 : array
{
    public array2(int [] arr):base(arr)
    {
    }
    public double Average()
    {
        return 
    }
}

Now, in the derived class I need to get the average of the array and I can't do arr.Average() The error says: Error 1 'ConsoleApplication1.array.arr' is inaccessible due to its protection level C:\Users\x\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 35 20 ConsoleApplication1 Anyone can tell me what am I doing wrong? Thanks for helpers!


arr is declared as private since you didn't specify a visibility type. If you change it to protected, then your subclass array2 will be able to access it.

protected int [] arr;


In your example, you've made the arr array implictly private where you have omitted the modifier itself. If you want to provide access to said field in your derived classes, you'd need to use an access modifier of protected:

protected int[] arr;

But it's not recommend to expose fields this way, as fields should really be for private class state. What you should do, is encapsulate read-only access to that field, via a property:

protected int[] Array { 
    get { return this.arr; }
}

Which means in your derived class, you can:

public double Average()
{
    return this.Array.Average();
}


In C#, the default access level for a class member is private. You haven't specified an access level for int [] arr, so it is private and hence visible to the other class.


That's because your arr field is private. consider using a write-private read-protected property instead, like this:

class array
{
    protected int[] arr {get; private set; }
    public array(int[] arr)
    {
        this.arr = arr;
    }
    public int Biggest()
    {
        return arr.Max();
    }
    public int Min()
    {
        return arr.Min();
    }
    public int SumArr()
    {
        return arr.Sum();
    }
}
class array2 : array
{
     public array2(int [] arr):base(arr)
     {
     }
     public double Average()
     {
        return arr.Average();
     }
}


Since you didn't explicitly define an access type for arr, it is implicitly set to private. To be able to access this from the derived class, you should set it to protected.

protected int [] arr;

There are better ways to do this, e.g. through a property, but that's the general idea.


Add public or protected to the arr variable:

public int [] arr; 
protected int [] arr; 

If you don't specify otherwise, the compiler will default to making your declarations private.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜