#include <iostream>
#include <stdexcept>
#include <string>
int main() {
setlocale(LC_ALL, "RU");
class Flower {
private:
std::string name; // Приватное поле
int petals; // Приватное поле
public:
Flower(const std::string& name, int petals) {
setName(name);
setPetals(petals);
}
void setName(const std::string& name) {
this->name = name;
}
std::string getName() const {
return name;
}
void setPetals(int petals) {
if (petals < 0) {
throw std::invalid_argument("Количество лепестков не может быть отрицательным.");
}
this->petals = petals;
}
int getPetals() const {
return petals;
}
};
// Производный класс
class Rose : public Flower {
private:
std::string color; // Новое поле
public:
Rose(const std::string& name, int petals, const std::string& color)
: Flower(name, petals), color(color) {}
void display() const {
std::cout << "Роза: " << getName() << ", Лепестки: " << getPetals() << ", Цвет: " << color << std::endl;
}
};
// Класс, основанный на двух других
class Bouquet : public Rose {
private:
int quantity; // Новое поле
public:
Bouquet(const std::string& name, int petals, const std::string& color, int quantity)
: Rose(name, petals, color), quantity(quantity) {}
void showBouquet() const {
display();
std::cout << "Количество: " << quantity << std::endl;
}
};
// Класс, наследующий от Rose
class SpecialRose : public Rose {
public:
using Rose::Rose; // Наследуем конструктор
private:
// Доступ к полям базового класса ограничен
void setColor(const std::string& color) {
// Метод для изменения цвета, доступен только в классе
}
};
// Основная функция
try {
Flower flower("Тюльпан", 5);
flower.setPetals(10);
std::cout << "Цветок: " << flower.getName() << ", Лепестки: " << flower.getPetals() << std::endl;
Rose rose("Роза", 8, "Красный");
rose.display();
Bouquet bouquet("Букет", 6, "Белый", 12);
bouquet.showBouquet();
SpecialRose specialRose("Специальная Роза", 7, "Синий");
// specialRose.setColor("Зеленый"); // Это вызовет ошибку, так как метод недоступен в main
}
catch (const std::invalid_argument& e) {
std::cerr << "Ошибка: " << e.what() << std::endl;
}
return 0;
}