Preview:
#include <iostream>
#include <stdexcept>
#include <string>

int main() {
	setlocale(LC_ALL, "RU");

	class Car {
	private:
		std::string name; // Приватное поле
		int mx_speed; // Приватное поле

	public:
		Car(const std::string& name, int mx_speed) {
			setName(name);
			setMaxspeed(mx_speed);
		}

		void setName(const std::string& name) {
			this->name = name;
		}

		std::string getName() const {
			return name;
		}

		void setMaxspeed(int mx_speed) {
			if (mx_speed < 0) {
				throw std::invalid_argument("Скорость машины не может быть отрицательной.");
			}
			this->mx_speed = mx_speed;
		}

		int getMaxspeed() const {
			return mx_speed;
		}
	};

	// Производный класс
	class Porshe : public Car {
	private:
		std::string color; // Новое поле

	public:
		Porshe(const std::string& name, int mx_speed, const std::string& color)
			: Car(name, mx_speed), color(color) {}

		void display() const {
			std::cout << "Porshe: " << getName() << ", Максимальная скорость: " << getMaxspeed() << ", Цвет: " << color << std::endl;
		}
	};

	// Класс, основанный на двух других
	class Price : public Porshe {
	private:
		int cost; // Новое поле

	public:
		Price(const std::string& name, int mx_speed, const std::string& color, int cost)
			: Porshe(name, mx_speed, color), cost(cost) {}

		void showPrice() const {
			display();
			std::cout << "Цена: " << cost << std::endl;
		}
	};

	// Класс, наследующий от Rose
	class SpecialPorshe : public Porshe {
	public:
		using Porshe::Porshe; // Наследуем конструктор

	private:
		// Доступ к полям базового класса ограничен
		void setColor(const std::string& color) {
			// Метод для изменения цвета, доступен только в классе
		}
	};

	// Основная функция
	try {
		Car car("Porshe Cayenne", 260);
		car.setMaxspeed(300);
		std::cout << "Машина: " << car.getName() << ", Максимальная скорость: " << car.getMaxspeed() << std::endl;

		Porshe porshe("Porshe Macan", 330, "Голубой");
		porshe.display();

		Price price("Porshe Panamera", 250, "Белый", 3000000);
		price.showPrice();

		SpecialPorshe specialPorshe("Porshe 911", 330, "Синий");
		// specialRose.setColor("Зеленый"); // Это вызовет ошибку, так как метод недоступен в main

	}
	catch (const std::invalid_argument& e) {
		std::cerr << "Ошибка: " << e.what() << std::endl;
	}

	return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter