gpt4 book ai didi

c++ - 在cpp中实例化一个新对象

转载 作者:行者123 更新时间:2023-11-28 00:10:51 25 4
gpt4 key购买 nike

我有 3 个名为 Starter、Pizza 和 Dessert 的类,它们在创建对象时接受可变数量的字符串输入,例如,

//pizza takes 2 inputs
Pizza p("margarita","large size");

//starter takes 3 inputs
Starter s("ribs","bbq sauce","small size");

但我想使用函数 add() 创建一个 new 对象,该函数接受一个字符串并将其与类匹配以创建一个新对象。例如

add(string type)
{
if(type == "Pizza")
{
Pizza *p = new Pizza();
}

else if(type == "Starter ")
{
Starter *p = new Starter ();
}
}

现在我的问题是,如何以用户友好的方式向类提供输入?通过用户友好,我认为用户可以在一行中编写一个类的所有输入,而不是使用 cin 来获取每个输入。

假设我们要披萨,然后是我不想要的,

cout<<"What type of pizza";
cin>>*input* <<endl;
cout<<"What size";
cin>>*input* <<endl;

我想将所有输入写在一行中,例如

输入 "margarita","large"

最佳答案

// Read complete string.
// Eg. margarita large
string order;
getline(cin, order);

// It automatically parses string based on space
istringstream is(order);
string meal, size;
is >> meal;
is >> size;

关于c++ - 在cpp中实例化一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33210493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com