@Hikkirray

List убирает string значения из класса, что делать?

#include <iostream>
#include <string>
#include <locale.h>
#include <vector>
#include <list>
using namespace std;

class Appliances {
protected:
	string model;
	string producer;
	unsigned int price;
	unsigned int year;
	int id;
public:
	Appliances(string model, string producer, unsigned int price, unsigned int year) {

		this->model = model;
		this->price = price;
		this->producer = producer;
		this->year = year;
		this->id = rand();

	}
	virtual void Print() {

		cout << "Название модели: " << this->model << endl;
		cout << "Название производителя: " << this->producer << endl;
		cout << "Цена: " << this->price << endl;
		cout << "Год выхода: " << this->year << endl;

	}
	void StatChangesModel() {
		cout << "Введите модель:";
		cin >> this->model;
	}
	void StatChangesProducer() {
		cout << "Введите производителя:";
		cin >> this->producer;
	}
	string GetModel() {
		return this->model;
	}
	string GetProducer() {
		return this->producer;
	}
	unsigned int GetPrice() {
		return this->price;
	}
	unsigned int GetYear() {
		return this->year;
	}
	int GetId() {
		return this->id;
	}
};


class Microwave: public Appliances {
public:
	Microwave(string model, string producer, unsigned int price, unsigned int year): Appliances(model, producer, price, year) {

		this->model = model;
		this->price = price;
		this->producer = producer;
		this->year = year;
		this->id = rand();
	}
	void Print() {

		cout << "Микроволновка:" << endl;
		cout << "Название модели: " << this->model << endl;
		cout << "Название производителя: " << this->producer << endl;
		cout << "Цена: " << this->price << endl;
		cout << "Год выхода: " << this->year << endl;

	}
	void StatChangesModel() {
		cout << "Введите модель:";
		cin >> this->model;
	}
	void StatChangesProducer() {
		cout << "Введите производителя:";
		cin >> this->producer;
	}
	string GetModel() {
		return this->model;
	}
	string GetProducer() {
		return this->producer;
	}
	unsigned int GetPrice() {
		return this->price;
	}
	unsigned int GetYear() {
		return this->year;
	}
	int GetId() {
		return this->id;
	}
};

class IceBox : public Appliances {
public:
	IceBox(string model, string producer, unsigned int price, unsigned int year) : Appliances(model, producer, price, year) {
		
		this->model = model;
		this->price = price;
		this->producer = producer;
		this->year = year;
		this->id = rand();
	}
	void Print() {
		
		cout << "Холодильник:" << endl;
		cout << "Название модели: " << this->model << endl;
		cout << "Название производителя: " << this->producer << endl;
		cout << "Цена: " << this->price << endl;
		cout << "Год выхода: " << this->year << endl;

	}
	void StatChangesModel() {
		cout << "Введите модель:";
		cin >> this->model;
	}
	void StatChangesProducer() {
		cout << "Введите производителя:";
		cin >> this->producer;
	}
	string GetModel() {
		return this->model;
	}
	string GetProducer() {
		return this->producer;
	}
	unsigned int GetPrice() {
		return this->price;
	}
	unsigned int GetYear() {
		return this->year;
	}
	int GetId() {
		return this->id;
	}
};


void main() {
	setlocale(LC_ALL, "rus");

	list <Appliances*> catalog;
	do
	{
		int switch_on;
		string producer, model;
		unsigned int price;
		unsigned int year;
		cout << "1 - добавить указатель на бытовую технику" << endl << "2 - Добавить указатель на микроволновку" << endl << "3 - Добавить указатель на холодильник" << endl << "4 - Вывести каталог" << endl << "5 - Выйти из программы" << endl;
		cout << "Введите действие: ";
		cin >> switch_on;
		switch (switch_on)
		{
		case 1: {
			cout << endl << "Введите модель:";
			cin >> model;
			cout << endl << "Введите прозводителя:";
			cin >> producer;
			cout << endl << "Введите цену:";
			cin >> price;
			cout << endl << "Введите год выхода:";
			cin >> year;
			Appliances appliances{ model,producer,price,year };
			Appliances* pb = &appliances;
			catalog.push_back(pb);
			break;
		}
		case 2: {
			cout << endl << "Введите модель:";
			cin >> model;
			cout << endl << "Введите прозводителя:";
			cin >> producer;
			cout << endl << "Введите цену:";
			cin >> price;
			cout << endl << "Введите год выхода:";
			cin >> year;
			Microwave microwave{ model,producer,price,year };
			Appliances* px = &microwave;
			catalog.push_back(px);
			break;
		}
		case 3: {
			cout << endl << "Введите модель:";
			cin >> model;
			cout << endl << "Введите прозводителя:";
			cin >> producer;
			cout << endl << "Введите цену:";
			cin >> price;
			cout << endl << "Введите год выхода:";
			cin >> year;
			IceBox icebox{ model,producer,price,year };
			Appliances* pb = &icebox;
			catalog.push_back(pb);
			break;
		}
		case 4:{
			for (Appliances* i : catalog) {
				i->Print();
			}
			break;
		}
		case 5: {
			exit(0);
		}
		}
	} while (true);
	//Appliances appliances{ "dexp","samsung",123,123 };
	//IceBox keyboard{"dexp", "asus", 123, 213};
	//Microwave monitor{"dexp", "asus", 123, 123};
	///*Appliances *appliances_u =  &appliances;
	//appliances_u->Print();
	//appliances_u = &keyboard;
	//appliances_u->Print();*/

}
  • Вопрос задан
  • 85 просмотров
Решения вопроса 1
@dima20155
you don't choose c++. It chooses you
Во-первых, зачем вы приводите целый исходник сюда. Люди куда быстрее поймут суть, если вы сократите иерархию классов до демонстративного минимума.

Во-вторых, во всех ваших case'ах
Создается временный объект, затем вы зачем-то создаете ещё и временную переменную-указатель и сохраняете его адрес (зачем?). А после запихиваете все это в лист. Объект создается на стеке и при выходе за границы фигурных скобок вызывается деструктор и он перестает существовать, а все его содержимое будет перезаписано любой следующей переменной, размешенной на стеке. Вот код, о котором я говорю:
case 1: {
      cout << endl << "Введите модель:";
      cin >> model;
      cout << endl << "Введите прозводителя:";
      cin >> producer;
      cout << endl << "Введите цену:";
      cin >> price;
      cout << endl << "Введите год выхода:";
      cin >> year;
      Appliances appliances{ model,producer,price,year };
      Appliances* pb = &appliances;
      catalog.push_back(pb);
      break;
    }


Вот наглядный пример того что у вас получается.
https://godbolt.org/z/bx5Wbo1bG

Как исправить? Создавайте элемент в куче (new OhMyClass()). А лучше храните в std::list, например, std::unque_ptr
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы