簡體   English   中英

通過輸入創建 C++ 對象

[英]C++ Object Creation through Inputs

我想用輸入的名稱創建一個類的對象

class Rectangle {
public:
 int width;
 int height;
 ...
 //assume a constructor that assigns (width, height)
}

我將如何使用輸入生成一個新名稱的對象。 (不是我輸入Rectangle myRectangle(1,1);

假設用戶創建了從 1 到無限個對象

(我不是在尋求人工輸入的幫助,或者檢查他們是否仍然需要輸入,只是如何使用輸入來創建唯一命名的對象)

這是我的第一個堆棧溢出帖子,所以如果我做錯了什么,請通知我。

干杯,

煤小伙

您可以使用從(用戶提供的)類名到工廠函數的映射。

class Creatable {
  virtual ~Creatable() {}
};
class Rectangle : public Creatable {
  int width;
  int height;
};
class Circle : public Creatable {
  int radius;
};
// assume suitable constructors for these

// Given a string (with parameters such as the
// radius or width/height) construct an object
// and return a managed pointer to it
using FactoryFunction_t =
    std::function<std::unique_ptr<Creatable>(std::string const &)>;

// maps for example "rectangle" to a function which parses width and height from the string and returns an allocated rectangle
std::map<std::string, FactoryFunction_t> factories;
factories.insert({{"rectangle", CreateRectangle}, {"circle", CreateCircle}});

factories.at("rectangle")("width=21; height=42;");

如果可能的類在編譯時已知,那么您也可以使用std::variant代替使用多態性(一個公共基類)。

除了讓每個工廠函數解析一個字符串之外,您還可以在之前解析參數 - 例如轉換為映射參數名稱 -> 參數值並將其傳遞給工廠函數。

如果您想讓用戶命名創建的對象,那么您可以將上面的托管指針保留在地圖中:

std::map<std::string, std::unique_ptr<Creatable>> objects;

objects["my_rectangle"] = factories.at("rectangle")("width=21; height=42;");

這可能是用戶輸入的結果,類似於:

my_rectangle = 矩形(寬度=21;高度=42;);

#include<vector>
class Rectangle {
public:
 int width;
 int height;
};

int main(){
/*You can't use unique names. You can use a vector of objects
 std::vector<Rectangles> rectsVector; and then when you want
 to create anew object ask the user for (width,height) then
 rectVector.push_back(Rectangle{width,height}) and so on*/

    std::vector<Rectangle> rectsVector;
    size_t width{3},height{2};
    rectsVector.push_back(Rectangle{width,height});
    return 0;
}

暫無
暫無

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

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