2014-09-29 19 views
0

我只是覺得現在真的很笨,你能幫我解釋爲什麼我用這個簡單的代碼有保護級別問題嗎?我甚至試圖把它通過對象,但仍然保護水平問題。這個簡單的程序爲什麼會給我提供保護級別的問題?

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(); 
    } 
} 
+0

這就是爲什麼你不使用隱含的知名度。 – Mephy 2014-09-29 05:13:48

+2

「保護等級問題」是什麼意思? – 2014-09-29 05:13:52

+0

就像它基本上突出顯示功能中的「第一,第二,添加」,並且說a.second,a,first和a.add由於其保護級別而不可訪問,但是該函數是公開的,並且我沒有聲明整數作爲私人 – 2014-09-29 05:16:30

回答

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,這將是空的顯示。

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

乾杯

1

不知道你在說什麼「保護」問題有關,而是因爲它有{3}但你只有3個參數,你會得到在運行時異常在display方法 - 應該是{2}

另外,您正在顯示bcall,但在acall上執行該操作,因此在打印時它將打印全零。

編輯現在我明白你在說什麼了,威廉的回答解決了這個問題。

+0

謝謝你喬:) – 2014-09-29 05:22:01

+0

lolyou是正確的它的打印全零,所以我如何從用戶在A類的整數,然後顯示結果在B類?沒有變零?這意味着我可以在課堂上完成作品並在課堂上展示結果嗎? – 2014-09-29 05:24:14

+0

我不知道你的現實世界的場景,但在這個例子中,沒有理由有兩個對象。所有你需要的僅僅是單個'B'對象:'B bcall = new B(); bcall.input(); bcall.sum(); bcall.display();' – 2014-09-29 06:07:24

5

由於字段的默認可見性是「私人」。

您沒有明確指定「first」,「second」和「add」的可見性,所以「first」,「second」和「add」是類A的私有字段,不可見B級。

+0

謝謝威廉 – 2014-09-29 05:19:09

相關問題