为什么这个简单的程序会给我保护级别问题?

时间:2014-09-29 05:08:46

标签: c# inheritance polymorphism accessor

我现在觉得自己真的很蠢可以请你帮我解释为什么我这个简单的代码有保护级问题?我甚至尝试通过对象调用它,但仍然保护级别问题。

class A
{
    int first, second, add;

    public void input()
    {
        Console.WriteLine("Please enter the first number: ");
        first = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Please enter the second number: ");
        second = Convert.ToInt32(Console.ReadLine());
    }

    public void sum()
    {
        add = first + second;
    }
}

class B : A 
{       
    public void display()
    {
        Console.WriteLine("You entered {0} and {1} the sum of two numbers is {3}",first,second,add); //<<<<<<<< here

    }
}

class Program
{
    static void Main(string[] args)
    {
        A acall = new A();
        B bcall = new B();

        acall.input();
        acall.sum();
        bcall.display();
    }
}

3 个答案:

答案 0 :(得分:5)

因为字段的默认可见性是&#34; private&#34;。

您没有明确指定可见性,因为&#34;首先&#34;,&#34;秒&#34;并且&#34;添加&#34;,所以&#34;首先&#34;,&#34;第二&#34;,&#34;添加&#34;是A类的私有字段,在B类中不可见。

答案 1 :(得分:1)

不知道&#39;保护&#39;您正在谈论的问题,但是您在display方法中会在运行时遇到异常,因为它有{3}但您只有3个参数 - 应该是{ {1}}。

另外,您正在显示{2},但正在对bcall进行处理,因此在打印时,它会打印全部为零。

编辑现在,我看到了您正在谈论的内容,Willem的回答解决了这个问题。

答案 2 :(得分:1)

您的问题是其他人声明字段为private,因此无法从B类访问。将其更改为protected

class A
{
    protected int first;
    protected int second;
    protected int add;

    public void input()
    {
        Console.WriteLine("Please enter the first number: ");
        first = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Please enter the second number: ");
        second = Convert.ToInt32(Console.ReadLine());
    }

    public void sum()
    {
        add = first + second;
    }
}

class B : A 
{
    public void display()
    {
        Console.WriteLine("You entered {0} and {1} the sum of two numbers is {3}",first,second,add); // here you go
    }
}

现在,您在这里创建了两个不同的类,从acall获取输入,然后在另一个类bcall上调用display,这将是空的。

class Program
{
    static void Main(string[] args)
    {
        B bcall = new B();
        bcall.input();
        bcall.sum();
        bcall.display();
    }
}

干杯

相关问题