Я работаю над некоторыми примерами экзаменов для экзамена по программированию на С ++, и пример, в котором я застрял, требует от меня написания класса для возврата содержимого объекта "Closet".Один из методов, требуемых в этом примере, добавляет вектор объектов Garment ко второму вектору объектов Garment (то есть заполняет шкаф одеждой).До этого момента мой код проходил все предоставленные мне ссылки и проверки (список с предполагаемыми ошибками во время выполнения и инструкциями cout / cerr), поэтому я удалил определения методов и вызовы в коде, который я публикую.здесь, чтобы показать только ту часть, где я получаю неожиданные результаты.
Я предполагал, что один из конструкторов или даже другой метод может помешать выводу, поэтому я выполнил несколько версий кода черезвизуализатор (Python tutor для c ++), но он также не пролил никакого нового понимания, никакие другие методы не были вызваны (как и ожидалось), и никакой другой вывод не был получен от конструкторов.
#include <iostream>
#include <stdexcept>
#include <vector>
#include <string>
using namespace std;
enum class Color{Red, Blue, Gray, Yellow};
const std::vector<std::string> color_names{"red", "blue", "gray", "yellow"};
enum class Type{Pants, Blouse, Shirt, Skirt};
const std::vector<std::string> type_names{"pants", "blouse", "shirt", "skirt"};
class Garment {
int preis;
Color farbe;
Type typ;
public:
//Konstruktor
Garment (int p, Color f = Color::Gray, Type t = Type::Pants){
this->preis = p;
this->farbe = f;
this->typ = t;
//negativer Preis = exception
if (p < 0){throw runtime_error("Preis kleiner als 0!");} }
int get_price() const{
return this->preis; }
Type get_type() const{
return this->typ; }
bool has_color(Color f) const{}
void deteriorate(int w){}
int get_index_color() const{}
int get_index_type() const{}
friend ostream& operator<<(ostream& out, const Garment &g){
//[40000 Cent, yellow blouse]
out << "[" << g.preis << " Cent, "<< color_names[g.get_index_color()]
<< " " << type_names[g.get_index_type()];
out << "]";
return out;
}
};
class Closet {
size_t capacity;
vector<Garment> inventory;
public:
//Konstruktor Beginn
Closet (size_t c, vector<Garment> inv){
this->capacity = c;
this->inventory = inv;
if (capacity < 5 || capacity > 300){throw runtime_error ("Komplette Kapazitaet ueber oder unterschritten!");}
if (this->inventory.size() > this->capacity){throw runtime_error ("Relative kapazitaet ueberschritten");}
vector<int>kleiderliste {0,0,0,0};
for (auto x : inv){
if (x.Garment::get_type() == Type::Pants){kleiderliste[0]++;}
if (x.Garment::get_type() == Type::Blouse){kleiderliste[1]++;}
if (x.Garment::get_type() == Type::Skirt){kleiderliste[2]++;}
if (x.Garment::get_type() == Type::Shirt){kleiderliste[3]++;}
}
int zaehler = 0;
for (auto y : kleiderliste){
if (y != 0 ){zaehler++;}
}
if (zaehler <2){throw runtime_error("Nur mehr kleidungsstuecke eines typs im schrank");}
}
bool add(vector<Garment> v){
if ((v.size() + this->inventory.size()) <= this->capacity){
cerr << 1;
this->inventory.insert(this->inventory.begin(),v.begin(),v.end());
return true;
}else{
cerr << 0;
return false;
}
}
double mean_price() const{
}
friend ostream & operator<<(ostream &out,const Closet &c){
out << "[" << c.capacity << ",{";
for (auto x : c.inventory){
out <<x;
}
out << "},";
out << c.mean_price();
out << "]";
return out;
}
};
int main(){
Garment pants{34500, Color::Blue, Type::Pants};
Garment blouse{12700, Color::Red, Type::Blouse};
const Garment shirt{2300, Color::Yellow, Type::Shirt};
Garment shirt2{23500, Color::Red, Type::Shirt};
Garment skirt{26600, Color::Gray, Type::Skirt};
Garment skirt2{4600, Color::Blue, Type::Skirt};
Closet closet {10, {skirt, blouse, shirt, pants, skirt}};
cout << closet.add({shirt2, skirt2}) << closet.add({blouse,skirt,pants}) << closet.add({}) << closet.add({pants}) << '\n';
return 0; }
Этот коддолжен выдавать следующий вывод через cout: 1110. Метод Closet :: add должен возвращать true три раза и false один раз подряд.
То, что я на самом деле получаю как возвращаемые значения через cout <<, это: 0111 Чтобы проверить, выполняет ли код то, что он должен, я вывожу 1 для true и 0 для false также на канале cerr, и там яполучить правильные 1110 чисел. </p>
Что приводит к тому, что возвращаемый результат не будет 1110?Вызовы методов выполняются в ином порядке в компиляторе?