好的,在我學習的時候帶上我和男孩和女孩。這是我的問題。重寫和繼承的幫助
我想不通爲什麼我不能重寫父類的方法。這裏是基類的代碼(是的,我從OOP書中竊取了Java代碼,並試圖用C#重寫它)。
using System;
public class MoodyObject
{
protected String getMood()
{
return "moody";
}
public void queryMood()
{
Console.WriteLine("I feel " + getMood() + " today!");
}
}
,這裏是我的其他2個對象繼承基類(MoodyObject):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class SadObject: MoodyObject
{
protected String getMood()
{
return "sad";
}
//specialization
public void cry()
{
Console.WriteLine("wah...boohoo");
}
}
}
和:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class HappyObject: MoodyObject
{
protected String getMood()
{
return "happy";
}
public void laugh()
{
Console.WriteLine("hehehehehehe.");
}
}
}
,這裏是我的主:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MoodyObject moodyObject = new MoodyObject();
SadObject sadObject = new SadObject();
HappyObject happyObject = new HappyObject();
Console.WriteLine("How does the moody object feel today?");
moodyObject.queryMood();
Console.WriteLine("");
Console.WriteLine("How does the sad object feel today?");
sadObject.queryMood();
sadObject.cry();
Console.WriteLine("");
Console.WriteLine("How does the happy object feel today?");
happyObject.queryMood();
happyObject.laugh();
}
}
}
正如你所看到的,很基本的東西,但是h ere的輸出:
今天的喜怒無常的對象感覺如何? 今天我感到喜怒無常!
今天的悲傷對象有什麼感覺?我 今天感到喜怒無常! wah ... boohoo
今天快樂的對象有什麼感覺? 今天我感到喜怒無常! hehehehehehe。 按任意鍵繼續。 。 。
不符合我的預期。我試圖使基本方法虛擬和調用重寫時,試圖重寫它,只是讓我這個錯誤「不能重載繼承成員'MoodyObject.getMood()',因爲它沒有標記虛擬,抽象或重寫」。我也嘗試過沒有虛擬和覆蓋,它認爲我試圖隱藏基本方法。再次,我是OOP的新手,並會感謝任何指導。
編輯添加:我找到了! MoodyObject.cs只是解決方案資源管理器中的一個「解決方案項目」,而不是「ConsoleApplication1」項目。我把它拖到它屬於解決方案資源管理器的地方,瞧!它現在有效。我將盧克的答案標記爲答案,因爲他提供了我需要的幫助,以便我解決問題......我在這裏學到了很多東西。這是驚人的,你們和女孩都瘋了!
感謝您將我的答案標記爲已接受的答案,但是我可能會建議您選擇一個不太詳細且比我的信息更多的信息(例如Ilya's或Josh's)? – 2008-12-03 16:32:17
如你所願。再次感謝Luc – GregD 2008-12-03 17:05:08