2013-08-12 21 views
3
Ship *ship; 

    if (newShipType == 0) 
    { 
    ship = new SmallShip(gridPosition.x, gridPosition.y, 
         grid->raw); 
    } 
    else if (newShipType == 1) 
    { 
    ship = new MediumShip(gridPosition.x, gridPosition.y, 
          grid->raw); 
    } 
    else // 2 
    { 
    ship = new BigShip(gridPosition.x, gridPosition.y, 
         grid->raw); 
    } 

的我有一個代碼,我想沿着東西線,以簡化:陣列實際類

Ship *ship = new getShipByType[newShipType](gridPosition.x, gridPosition.y, grid->raw); 

是類似的東西可能嗎?

Ship getShipByType[3] = {SmallShip, MediumShip, BigShip}; 

這給:

error: expected primary-expression before ‘,’ token 
error: expected primary-expression before ‘,’ token 
error: expected primary-expression before ‘}’ token 

我真的不指望它來編譯,只是爲了尋找這樣的一個簡單的方法,它只是一個很長的出手嘗試。

+5

閱讀「工廠模式」。它可能會幫助你。 – arne

+6

OP當然應該閱讀「造船廠模式」? –

+1

總之;沒有。但正如arne說你應該考慮工廠模式。 – dutt

回答

2

我提議實施船舶建立一個工廠,是這樣的:

enum ShipSize { Small, Medium, Big}; 

class ShipFactory 
{ 
public: 
    // consider return std::unique_ptr, shared_ptr or std::auto_ptr 
    Ship * createShip(ShipSize size) 
    { 
     switch (size) 
     { 
      case Small: return new SmallShip(); 
      ... 
     } 
    } 
}; 

要自動內存管理,你也可以考慮返回的std ::的unique_ptr(如果你使用新的編譯器,或shared_ptr的,或如果你有舊的auto_ptr)。

1

假設SmallShipMediumShipBigShipShip不同派生類,可以不是實例存儲在Ship變量。它必須是一個參考或指針。

正如在評論中提到的那樣,工廠函數絕對是一個可能的解決方案(但是,除了應該是我的書中的枚舉類型的硬編碼數字之外,它幾乎就是您的第一個代碼段)。

5

您可以委託一個函數來創建不同的船隻,通常稱爲工廠模式。另外array不處理多態,你需要用vector來代替:

#include <memory> 

enum ShipType { Small = 0, Medium, Big }; 

std::unique_ptr<Ship> makeShip(ShipType ship_type, GridPosition position) 
{ 
    switch(ship_type) 
    { 
    case Small: 
     return std::unique_ptr<Ship>(new SmallShip()); 
    break; 
    case Medium: 
     return std::unique_ptr<Ship>(new MediumShip()); 
    case Big 
     return std::unique_ptr<Ship>(new BigShip()); 
    default: 
     break; 
    } 
    return nullptr; 
} 

std::vector<std::unique_ptr<Ship>> ships; 
ships.push_back(makeShip(Samll)); 
ships.push_back(makeShip(Medium)); 
ships.push_back(makeShip(Big)); 
// now fly your ship!!! 
+0

應該是'std :: unique_ptr ' – Paranaix

+0

@Paranaix是的,我也想make_unique,但是,make_unique在C++ 11中不可用,這就是爲什麼我簡單地返回原始指針以使返回看起來更簡單:) – billz

+0

但是即時通訊相當肯定,上面的代碼不會編譯和缺乏'make_unique'不是一個問題,或者'std :: unqiue_ptr'可以從'T *'實現構造' – Paranaix

3

你可以使用一個函數指針數組。

將一個靜態模板函數添加到Ship將允許它作爲工廠。

typedef std::unique_ptr<Ship> (*fnShipCreate)(int,int,void*); 
template <class T> static std::unique_ptr<Ship> create(int x, int y, void* raw) { return new T(x, y, raw); } 

(請注意,您沒有指定類型的構造函數的參數,所以我做了一個合理的猜測...)

這使得函數指針數組如下被指定,創建每種類型船舶的模板函數實例:

Ship::fnShipCreate shipCreators[] = { Ship::create<SmallShip>, 
             Ship::create<MediumShip>, 
             Ship::create<BigShip> }; 

,它可以使用(假設在原崗位的變量名)被稱爲:

std::unique_ptr<Ship> ship = shipCreators[newShipType](gridPosition.x, gridPosition.y, grid->raw);