Необходимо создать класс — зоомагазин. В классе должны быть следующие поля: животное ( напр. волк, пингвин, собака ), пол, имя , цена, количество. Включить в состав класса необходимый минимум методов, обеспечивающий полноценное функционирование объектов указанного класса:
- Конструкторы (по умолчанию, с параметрами, копирования);
- Деструктор;
- Переопределить возможные для класса операции, продумать порядок их выполнения;
- Добавить необходимые методы.
- Предоставить возможность вводить данные с клавиатуры или из файла (с помощью конструктора или операцией »).
К сожалению, решения данной задачи пока нет. Если Вы решили эту задачу, сообщите нам, и мы выложим её на сайте.
E-mail : admin@cppstudio.com
Комментарии
Oleg Alexseev
#include <iostream> #include <string> #include <vector> using namespace std; class Animal { public: Animal(); // Конструктор по умолчанию Animal(const Animal & object); // Конструктор копирования Animal(const string animal, const string name, const int sex, const double price); // Конструктор с параметрами ~Animal();// Деструктор static int getCount() { return Count; } int getId() { return id; } void outData(); void setAnimal(const string animal); void setName(const string name); void setSex(const int sex); void setPrice(const double price); void setData(const string animal, const string name, const int sex, const double price); string getAnimal(); string getName(); int getSex(); double getPrice(); private: static int Count; int id; string animal; int sex; string name; double price; string getnSex(const int sex); }; int Animal::Count = 0; Animal::Animal() : animal("none"), name("none"), sex(-1), price(-1) { Animal::Count++; id = Animal::Count; } Animal::Animal(const Animal & object) { this->animal = object.animal; this->name = object.name; this->sex = object.sex; this->price = object.price; Animal::Count++; id = Animal::Count; } Animal::Animal(const string animal, const string name, const int sex, const double price) : animal(animal), name(name), sex(sex), price(price) { Animal::Count++; id = Animal::Count; } Animal::~Animal() { Animal::Count--; } void Animal::outData() { cout << animal << " " << name << " " << getnSex(sex) << " " << price << endl; } void Animal::setAnimal(const string animal) { this->animal = animal; } void Animal::setName(const string name) { this->name = name; } void Animal::setSex(const int sex) { this->sex = sex; } void Animal::setPrice(const double price) { this->price = price; } void Animal::setData(const string animal, const string name, const int sex, const double price) { this->animal = animal; this->name = name; this->sex = sex; this->price = price; } string Animal::getAnimal() { return animal; } string Animal::getName() { return name; } int Animal::getSex() { return sex; } double Animal::getPrice() { return price; } string Animal::getnSex(const int sex) { switch (sex) { case 0: return "Самка"; case 1: return "Самец"; default: return "Неизвестно"; } } void outMenu(); int inNum(); int main() { setlocale(LC_ALL, "rus"); vector <Animal> vecAnimal; string cmd; string tanimal, tname; int tsex; double tprice; while (true) { outMenu(); cout << ">"; cin >> cmd; if (cmd == "q" || cmd == "quit") break; switch (atoi(cmd.c_str())) { case 1: if (!Animal::getCount()) { cout << "Информаця не найдена." << endl; } for (int i = 0; i < Animal::getCount(); i++) { cout << i+1 << ") "; vecAnimal[i].outData(); } break; case 2: if (!Animal::getCount()) { cout << "Животных не найдено." << endl; break; } vecAnimal[inNum()].outData(); break; case 3: cout << "Введите тип: "; cin >> tanimal; cout << "Введите имя: "; cin >> tname; cout << "Введите пол (0/1): "; cin >> tsex; cout << "Введите цену: "; cin >> tprice; vecAnimal.emplace_back(tanimal, tname, tsex, tprice); break; default: break; } } system("pause"); return false; } void outMenu() { cout << "1) Вывести информацию о всех животных"; cout << "\n2) Вывести информацию о животном"; cout << "\n3) Добавить животное"; cout << "\n 'q' выход."; cout << endl; } int inNum() { int number; while (true) { cout << "Введите номер (1 - " << Animal::getCount() << "): "; cin >> number; if (number >= 1 && number <= Animal::getCount()) { return number - 1; } cout << "Ошибка." << endl; } }Alex_Gates
#include <iostream> #include <cstring> #include <iomanip> using namespace std ; class ZooMagazine { private: string name ; double price ; double quantity ; string sex ; public: ZooMagazine () { name = "Animal"; sex = "unknown" ; price = 0 ; quantity = 0 ; } void set () { cout << endl ; cout << "Animal type: " ; cin >> name ; cout << "SEX: " ; cin >> sex ; cout << "Price: " ; cin >> price ; cout << "Quantity: " ; cin >> quantity ; } void get () { cout << endl << "==============================================================" << endl <<"| " ; printf ("%15s%15s%15s%15s", "Animal Type ||" , "Sex ||", "Price ||" , "Quantity |" ) ; cout << endl << "==============================================================" << endl << "| " ; cout.width (11); cout << name << " ||"; cout.width (11); cout << sex << " ||"; cout.width (11); cout << fixed << setprecision (2) << price << " ||"; cout.width (11); cout << fixed << setprecision (2) << quantity << " |"; cout << endl << "==============================================================" << endl ; } } ; int main () { short select ; short i = -1; ZooMagazine obj [20]; char password [] = "Hayastan" ; char answer [20] ; cout << "Hello !! \n\n" ; do { cout << "1: Add Object \n" << "2: look objects\n" << "3: Modify (need admin permissions) \n" << "4: Exit \n\n" ; do { cout << "your choose: " ; cin >> select ; if (select < 1 || select > 4) cout << "Wrong choose...Try again \n" << endl ; } while (select < 1 || select > 4 ); switch (select) { case 1: i++ ; obj[i].set() ; break; case 2: if (i == -1) { cout << "There is nothing to show..." << endl ; break; } for (short j = 0; j <= i; j++ ) { obj [j].get() ; } break; case 3: do { cout << "Enter password (type exit to return to the main menu): " << endl ; scanf ("%20s" , answer) ; if (strcmp (password, answer) == 0) { int mod_select ; cout << "choose what object you want to modify: " ; cin >> mod_select ; obj [mod_select].set() ; break; } else if (strcmp ("exit", answer) == 0 ) break; else cout << "wrong password..try again\n" ; } while ( strcmp ("exit", answer) != 0 ); break ; case 4: cout << "Good luck..See ya" ; break; } system ("cls"); } while (select != 4 ); return 0; }gornyyvladimir
//Не заморачиваясь на интерфейсе с пользавателем, получилось примерно вот так: #include <iostream> #include <string> #include <vector> #include <memory> using namespace std; class Animal { public: Animal(const string & _Speciment,const string & _Name,const bool & _Sex, const int & _Years, const double & _Cost); virtual ~Animal(){} string GetName() const { return Name; } string GetSpeciment() const { return Speciment; } bool GetSex() { return Sex; } unsigned int GetYears() const { return Years; } double GetCost() const { return Cost; } void SetName(const string & _Name); void SetYears(const unsigned int & _Years); void SetCost (const double & _Cost); void Show() const; private: string Speciment; string Name; bool Sex; // 1 - М 0 - Ж unsigned int Years; double Cost; }; Animal::Animal(const string & _Speciment,const string & _Name,const bool & _Sex, const int & _Years, const double & _Cost) : Speciment(_Speciment), Name(_Name), Sex(_Sex), Years(_Years), Cost(_Cost) { } void Animal::SetName(const string & _Name) { if(_Name.empty()) return; Name=_Name; } void Animal::SetYears(const unsigned int & _Years) { if(_Years > 200) return; Years=_Years; } void Animal::SetCost (const double & _Cost) { if(_Cost < 0.0) return; Cost=_Cost; } void Animal::Show() const { cout<<"Вид: "<<Speciment<<"; Имя: "<<Name<<"; Возраст: "<<Years<<"; Стоимость: "<<Cost<<"; Пол: "<<(Sex ? "Man" : "Woman")<<"."<<endl; } typedef std::shared_ptr<Animal> AnimalSharedPtrType; typedef vector<AnimalSharedPtrType> VectorAnimalSharedPtrType; class AnimalListClass { private: VectorAnimalSharedPtrType VectorAnimalSharedPtr; AnimalListClass(const VectorAnimalSharedPtrType &VectorAnimalSharedPtr):VectorAnimalSharedPtr(VectorAnimalSharedPtr){} public: AnimalListClass(){} void AddAnimal(const AnimalSharedPtrType&AnimalSharedPtr) { for(auto i =VectorAnimalSharedPtr.begin();i<VectorAnimalSharedPtr.end();++i) { auto Curent=*i; if ( AnimalSharedPtr==Curent || ( (Curent->GetSpeciment()==AnimalSharedPtr->GetSpeciment()) &&(Curent->GetName()==AnimalSharedPtr->GetName()) &&(Curent->GetSex()==AnimalSharedPtr->GetSex()) &&(Curent->GetYears()==AnimalSharedPtr->GetYears()) ) ) { throw std::runtime_error("Животное уже есть в списке."); } } VectorAnimalSharedPtr.push_back(AnimalSharedPtr); } void DeleteAnimal(const AnimalSharedPtrType&AnimalSharedPtr) { for(auto i =VectorAnimalSharedPtr.begin();i<VectorAnimalSharedPtr.end();++i) { auto Curent=*i; if(AnimalSharedPtr==Curent) { VectorAnimalSharedPtr.erase(i); break; } } } void ShowAllAnimals () const { std::cout<<"Сейчас в списке "<<VectorAnimalSharedPtr.size()<<":"<<endl; for(auto i =VectorAnimalSharedPtr.begin();i<VectorAnimalSharedPtr.end();++i) { auto Curent=*i; Curent->Show(); } std::cout<<endl; } AnimalListClass GetAnimalsBySpeciment(const std::string& Speciment) { vector<AnimalSharedPtrType> AnimalSharedPtrForReturn; for(auto i =VectorAnimalSharedPtr.begin();i<VectorAnimalSharedPtr.end();++i) { auto Curent=*i; if ( Curent->GetSpeciment()==Speciment ) { AnimalSharedPtrForReturn.push_back(Curent); } } return AnimalListClass(AnimalSharedPtrForReturn); } AnimalListClass GetAnimalsBySex(const bool& Sex) { vector<AnimalSharedPtrType> AnimalSharedPtrForReturn; for(auto i =VectorAnimalSharedPtr.begin();i<VectorAnimalSharedPtr.end();++i) { auto Curent=*i; if ( Curent->GetSex()==Sex ) { AnimalSharedPtrForReturn.push_back(Curent); } } return AnimalListClass(AnimalSharedPtrForReturn); } }; class ZooClass { public: ZooClass() { } ~ZooClass() { } AnimalListClass AnimalList; }; int main() { try { ZooClass Zoo; AnimalSharedPtrType AnimalSharedPtr(new Animal("Собака","Шарик",true,1,123.45)); AnimalSharedPtrType AnimalSharedPtr1(new Animal("Кошка","Мурка",false,2,300.10)); AnimalSharedPtrType AnimalSharedPtr2(new Animal("Кролик","Каштан",true,1,500)); Zoo.AnimalList.AddAnimal(AnimalSharedPtr); Zoo.AnimalList.AddAnimal(AnimalSharedPtr1); Zoo.AnimalList.AddAnimal(AnimalSharedPtr2); cout<<"В магазине:"<<endl; Zoo.AnimalList.ShowAllAnimals(); Zoo.AnimalList.DeleteAnimal(AnimalSharedPtr); cout<<"В магазине:"<<endl; Zoo.AnimalList.ShowAllAnimals(); cout<<"Кошки:"<<endl; AnimalListClass CatAnimalList=Zoo.AnimalList.GetAnimalsBySpeciment("Кошка"); CatAnimalList.ShowAllAnimals(); cout<<"Мужчины:"<<endl; AnimalListClass ManAnimalList=Zoo.AnimalList.GetAnimalsBySex(true); ManAnimalList.ShowAllAnimals(); AnimalSharedPtr2->SetName("Нет клички"); cout<<"Мужчины:"<<endl; ManAnimalList.ShowAllAnimals(); cout<<"В магазине:"<<endl; Zoo.AnimalList.ShowAllAnimals(); } catch(std::exception&ex) { std::cerr<<ex.what(); } return 0; }NDC
Вот мой вариант
#include <iostream> #include <conio.h> #include <cstring> using namespace std; const int SIZE = 100; class zoo { public: char animal[40]; char name[25], sex; int price, amount; zoo(){ *animal = ''; *name = ''; price = amount = 0; sex = ''; } ~zoo(){}; void input(); }object[SIZE]; void manager(),add(),user(),init(); void display(),del(),fdel(),ring(); int main() { setlocale(LC_ALL,"Russian"); int select; cout << "Добро пожаловать!\n\n"; do{ cout << "Выберите польователя:" << endl; cout << "1. Менеджер\n"; cout << "2. Покупатель\n"; cout << "3. Выход из программы\n"; do{ cin >> select; if(select < 1 || select > 3) cout << "Введите корректного пользователя"; } while(select < 1 || select > 3); switch(select) { case 1: manager(); break; case 2: user(); break; default: cout << "\nДо свидания!"; getch(); } } while(select!=3); return 0; } void user() { int x; cout << "Добро пожаловать в \"Мир питомцев\"!\n"; do{ cout << "Выберите действие: \n"; cout << "1.Посмотреть ассортимент\n"; cout << "2.Позвать менеджера\n"; cout << "3.Выход в главное меню (ТОЛЬКО для менеджера)\n"; do{ cin >> x; } while(x<1 || x>3); x == 1 ? display() : ring(); } while(x!=3); } void manager() { char arr[40]; for(int x = 0;x<=3;++x) { cout << "Введите пароль: "; cin >> arr; if(strcmp(arr,"delta")) { cout << "\nНеверный пароль, попытайтесь ещё раз\n"; if(x == 3) { cout << "Вы исчерпали все попытки.\n"; return; } } else { cout << "Доступ получен\n"; break; } } int choice; do{ cout << "\nВыберите операцию: \n\n"; cout << "1. Добавить животное в ведомость\n"; cout << "2. Просмотр ведомости\n"; cout << "3. Удаление животного из ведомости\n"; cout << "4. Полная очистка ведомости (Для администратора!)\n"; cout << "5. Вернуться в главное меню\n"; do{ cin >> choice; if(choice < 1 || choice > 5) cout << "Некорректный выбор\n"; } while(choice < 1 || choice > 5); switch(choice) { case 1: add(); break; case 2: display(); break; case 3: del(); break; case 4: fdel(); break; } }while(choice!=5); return; } void add() { int i; for(i=0;i<SIZE;++i) { if(!*object[i].animal) break; } if(i==SIZE) { cout << "Список полон.\n"; return; } object[i].input(); return; } void zoo::input() { cout << "Введите животное: "; cin >> animal; cout << endl; cout << "Введите имя животного: "; cin >> name; cout << endl; cout << "Ввеите пол животного(M\\F): "; cin >> sex; cout << endl; cout << "Введите цену(в долларах): "; cin >> price; cout << endl; cout << "Введите количество: "; cin >> amount; cout << endl; return; } void display() { int t; for(t=0;t<SIZE;t++) { if(*object[t].animal) { cout << '\n' << endl; cout << object[t].animal << endl; cout << "Имя: " << object[t].name << endl; cout << "Пол: " << object[t].sex << endl; cout << "Стоимость: " << object[t].price << "$" << endl; cout << "Количество: " << object[t].amount << endl; } } return; } void fdel() { char x, arr[40]; for(int x = 0;x<=3;++x) { cout << "Введите пароль администратора: "; cin >> arr; if(strcmp(arr,"admin")) { cout << "\nНеверный пароль, попытайтесь ещё раз\n"; if(x == 3) { cout << "Вы исчерпали все попытки.\n"; return; } } else { cout << "Доступ получен\n"; break; } } cout << "Очистить весь список?(Y\\N)\n"; do{ cin >> x; }while(!strchr("yn",tolower(x))); if(x=='y') { init(); } else { return; } return; } void del() { char na[40]; cout << "Введите имя животного, которое вы хотите удалить: "; cin >> na; cout << endl; for(int i = 0;i < SIZE;i++) { if(!strcmp(object[i].name,na)) { *object[i].animal = ''; *object[i].name = ''; object[i].sex = ''; object[i].price = 0; object[i].amount = 0; } else if(i==SIZE) { cout << "Такого животного нет в списке, проверьте имя ещё раз" << endl; } } return; } void init() { for(int i = 0; i<SIZE; i++) { *object[i].animal = ''; *object[i].name = ''; object[i].price = object[i].amount = 0; object[i].sex = ''; } return; } inline void ring() { cout << '\a'; }