簡體   English   中英

使用具有指向派生類對象的指針的基類指針數組調用派生類方法

[英]Calling derived class methods using array of base class pointers which has pointers to derived class objects

我有一個基礎類Player和兩個派生類HumanComputer Player是具有純虛擬方法PlayMove的抽象類。

現在,在“ Game課程中,我想讓所有玩家參與其中。 很少有玩家會成為Human類型,而其他玩家將是Computer 我想以這樣的方式實現它-對於數組中的每個播放器,我將調用PlayMove並根據播放器的類型,調用其自己的PlayMove

例如,說array = {humanPlayer, computerPlayer} array[0].PlayMove()應該Human::PlayMove() array[1].PlayMove()應該Computer::PlayMove()

-

我做了什么 -

class Game
{
    Human &h;
    Computer &c;
    Player **allPlayers;
}

Game::Game()
{
    h = new Human();
    c = new Computer();
    // problem is occuriung in following three line
    allPlayers = new (Player*)[2];
    allPlayers[0] = h;
    allPlayers[1] = c;
}

我知道

Base *b;
Derived d;
b = &d;

這可行。 除了需要指針數組之外,這種情況有什么不同?

(為問題的長標題表示歉意。如果可以的話,請提出一個新標題)

我在您的代碼中看到了幾個錯誤。 我已在以下代碼中更正了此錯誤,

class Player
{};
class Human : public Player
{};
class Computer : public Player
{};

class Game
{
public:
    Game();
    Human *h;
    Computer *c;
    Player **allPlayers;
};

Game::Game()
{
    h = new Human();
    c = new Computer();
    // Following three lines are just fine
    allPlayers = new Player*[2];
    allPlayers[0] = h;
    allPlayers[1] = c;
}

參考必須在施工初始化清單中初始化。 另外,不允許引用臨時對象,因此

"Game::Game():h(new Human),c(new Computer)"

不被允許。 解決方案是使用指針h和c代替引用。

暫無
暫無

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

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