我正在为一堂课做期中考试。我需要初始化一个常量的对象数组,它将一个向量作为构造函数args。基本上,我想做类似于以下Java代码的事情:
final Pizza[] standardMenu = {
new Pizza(Arrays.asList(new Integer(1), new Integer(2), new Integer(3))),
new Pizza(Arrays.asList(new Integer(4), new Integer(5), new Integer(6)))};
除了Integer实例,我会传递Ingredient实例。有没有办法在C ++中做这样的事情?我的书和快速谷歌搜索都没有产生任何好结果。
我正在看的代码(C ++):
Ingredient standardIngredients[8] = {Ingredient("American Cheese", "Cheese that comes from America", 1.0), Ingredient("Swiss Cheese", "Cheese that is Swiss", 1.0),
Ingredient("Peperoni", "Does it need a description?", 2.0), Ingredient("Ground Beef", "Ground up beef", 3.0),
Ingredient("Onion", "Its a vegetable", 0.5), Ingredient("Black Olives", "Olives that possess the color of blackness", 0.5),
Ingredient("Jalapenios", "Spicy things", 0.5), Ingredient("Pickles", "Just because I can", 0.5)};
Pizza standardMenu[1] = {Pizza({standardIngredients[0], standardIngredients[1]}, "A string", 7.8)};
答案 0 :(得分:0)
这样的事可以帮助:
typedef vector<string> Pizza;
auto menu = vector<Pizza>{ Pizza{ "chorizo", "tomato", "pepperoni" },
Pizza{ "Ananas", "Ham" } };
或者如果您更喜欢菜单作为数组:
Pizza menu[] = { Pizza{ "chorizo", "tomato", "pepperoni" }, Pizza{ "Ananas", "Ham" } };
当然这是第一步,因为在这个模型中,披萨只是其各部分的总和。如果你想增加更多的信息,如比萨饼的价格,卡路里等,最好有一个专门的课程。
修改强>
根据您的其他信息,我建议以下课程:
class Ingredient {
string name;
string description;
double price;
public:
Ingredient(string n, string d, double p) : name(n), description(d), price(p) {}
};
class Pizza {
vector<Ingredient> ingredients;
string name;
double price;
public:
Pizza(vector<Ingredient>i, string n, double p) : ingredients(i), name(n), price(p) {}
};
您的初始化将适用于此。
答案 1 :(得分:0)
您可以为Pizza定义构造函数,该构造函数将Ingredient的向量作为参数,或者为Pizza定义initializer_list以节省一些输入。
还要注意使用std :: array。在大多数情况下,你不应该使用C风格的数组,STL容器可以做很好的事情,比如记住它们的大小。
#include <iostream>
#include <vector>
#include <array>
#include <initializer_list>
using namespace std;
class Ingredient {};
class Pizza {
public:
Pizza(initializer_list<Ingredient> l) : ing{l} {}
Pizza(vector<Ingredient> l) : ing{l} {}
private:
vector<Ingredient> ing;
};
int main()
{
const array<Pizza, 3> pizzas1 {
Pizza{Ingredient{}, Ingredient{}, Ingredient{}},
Pizza{Ingredient{}, Ingredient{}, Ingredient{}},
Pizza{Ingredient{}, Ingredient{}, Ingredient{}}
};
const array<Pizza, 3> pizzas2 {
Pizza{vector<Ingredient>{Ingredient{}}},
Pizza{vector<Ingredient>{Ingredient{}}},
Pizza{vector<Ingredient>{Ingredient{}}}
};
}
答案 2 :(得分:0)
这对我有用:
class Pizza
{
private:
std::vector<int> m_members;
public:
Pizza(std::vector<int> &members) : m_members(members)
{
}
};
const Pizza pizzaArray[] = { Pizza(std::vector<int>{1, 2, 3}),
Pizza(std::vector<int>{4, 5, 6}), };