簡體   English   中英

如何在C ++中檢查構造函數是否具有特定參數

[英]How to check if a constructor has a specific parameter in C++

我有一個名為Enemy的類,它具有三個構造函數。 它有一個默認值,一個帶有統計信息和一個項目,一個帶有統計信息。 我要完成的工作是建立一個可以檢測敵人是否有物品的功能。 我想我可以輕松地創建另一個參數,該參數包含它們擁有的項數的整數值,但是我真的很希望能夠僅檢查item參數,這樣就不必構造另一個構造函數參數。

另外,我想我也可以在項目類中放入一個1或0的參數,這將允許檢查以確定是否存在某個項目。

我希望能夠檢測到一個項目的原因是,如果敵人確實有一個項目,則會發生一個序列,告訴您該項目,然后讓您選擇是否撿起該項目。

只要您始終可以省略帶有默認值的指定參數(例如Nothing),任務可能就不會很復雜。 我們可以省略的參數應該是最后一個或省略的前一個。 因此,您所描述的相對適合:

class Stats
{
    public:
      // some stat methods and data
};


enum Item
{
   Nothing,
   Something1,
   Something2,
   Something3
};


class A
{
   explicit A(Item item = Nothing);
   A(const Stats& stats, Item item = Nothing);
};


A::A(Item item)
{
   // in both constructors just recognize if the item is Nothing
   if (item == Nothing)
   {
      // default, no item
   }
   else
   {
      // deal with an item
   }
}

因此,您的客戶代碼將能夠執行以下操作:

// we imply item != Nothing here
A one;                 // default
A two(item);           // with an item
A three(stats);        // with stats
A four(stats, item);   // with stats and an item

當然,您應該以某種方式指定項目和統計信息。

暫無
暫無

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

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