簡體   English   中英

從派生類調用基本構造函數時不確定參數

[英]Unsure about parameters when calling base constructor from derived class

在游戲中實現繼承時遇到了一些麻煩。 我認為最好引入繼承,因為這會使我的代碼更整潔並以邏輯方式進行組織。

從派生類的基類調用構造函數時,我面臨的atm問題是參數。

我將Paddle類用作基類,將Player類用作繼承Paddle的類。

代碼如下所示:

在Paddle類中...

//properties

  protected Texture2D pTexture;
  protected Vector2 pPosition;
  protected Vector2 pVelocity;


//constructor for Paddle class (only first line here, as the rest is irrelevant)

public Paddle(Texture2D newTexture, Vector2 newPosition, Viewport theViewport, Color newColour)

在播放器類中。

//properties
PlayerIndex pID;


//constructor for Player class (only first line here, as the rest is irrelevant)
public Player(PlayerIndex newID) : base()

在您提到它不起作用的原因之前,是因為在Player類中調用的基本構造函數im沒有任何參數,而在基類/ Paddle類中的構造函數卻具有任何參數,我明白這一點。 我面臨的問題是設置播放器的紋理,位置等,但是紋理,位置等在基類中,因為它們是Player和Enemy類(從Paddle繼承的另一個類,但類似)的常見屬性給玩家,因此現在只提一下)。 我也不知道在Player類中調用基本構造函數時應將什么作為參數。

感謝您的閱讀和預先的幫助:-)

我在以下更改的附加代碼:

public Player(PlayerIndex newID, Texture2D newTexture, Vector2 newPosition, Viewport theViewport, Color newColour)
        : base(newTexture, newPosition, theViewport, newColour)

要以這種方式使用構造函數,您必須將基本構造函數所需的所有信息提供給派生的構造函數,以便它可以這樣調用:

public Player(PlayerIndex newID, Texture2D newTexture, Vector2 newPosition, Viewport theViewport, Color newColour)

然后,您傳遞給基地:

public Player(PlayerIndex newID, Texture2D newTexture, Vector2 newPosition, Viewport theViewport, Color newColour) : base(newTexture, newPosition, theViewport, newColour);

顯然,這會使Player構造函數大很多。 為避免此問題,您可以在基類(不可覆蓋Init()上聲明一個Init()函數,該函數采用構造函數執行的所有參數,並在實例化后讓擁有的類調用它。 無論哪種方式,您最終都必須向班級提供所有信息。

讓我知道我是否可以澄清任何問題或進一步幫助!。

更新

  1. 是的, :base(...)語法實際上與編寫(如果是有效的C#)語法相同myBaseClassPointer = new base(...); (在這種情況下,基數為Paddle)。 同樣,這不是有效的C#。 使用非默認構造函數時,實際上必須使用:base實例化基類。 它以與直接實例化屬性相同的方式設置屬性,並且只要不將其標記為私有,就可以從派生類中使用它們(子類有點用詞不當,因為該術語通常是指組合)。

  2. 我不建議使用Init()函數,因為不能保證using類可以調用它。 話雖如此,它可以像這樣很好地工作:

     class Player { private bool initialized = false; public Player() {} public void Init(Texture2D newTexture, Vector2 newPosition, Viewport theViewport, Color newColour) { //All the stuff your constructor used to do initialized = true; } public void SomeFunctionUsingVariables() { if (initialized) { //Do whatever } } } 

唯一的好處是您不必將Init()所需的所有數據都傳遞給Player構造函數,因此這些字段的知識不需要存在於Player類本身中。 只要可以進行檢查,並且您還記得在實例化類中調用Init ,它就可以工作。

由於paddle對象具有PlayerEnemy共享的屬性,因此與繼承相比,組合是更好的選擇。 (通過繼承,您不能分割基礎對象,因為該對象是為每個對象獨立構造的)。實現涉及構造一個(共享的) Paddle ,然后將其傳遞給PlayerEnemy的c-tor。

我不確定為什么共享Paddle屬性,例如位置和速度。 ViewPort似乎是應該共享的唯一屬性。 如果是類似Pong之類的游戲,則每個玩家都有其自己的位置和速度,但是兩者都繪制在同一GUI組件上。 在這種情況下,Player和Enemy都是槳,並且繼承很好,但是隨后將ViewPort共享。 實現過程包括構造一個ViewPort並將其以及Player (或Enemy )的位置,速度等傳遞給Player (或Enemy )c-tor,然后將它們傳遞到基本的Paddle c-tor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM