Вопрос задан 27.10.2023 в 04:13. Предмет Информатика. Спрашивает Чубій Настя.

С++ Реализовать класс Машина. - Модель - Скорость - Цвет (лучше не строкой, а enum) От класса

машина унаследовать класс Грузовик. Грузовику добавить поле объем грузового отсека. Унаследоваться, правильно вызывать конструкторы, в мейне все потестить. Код:#include using namespace std; class Human { protected: string name; int age; public: Human() { cout << "Human default " << this << endl; age = 0; } Human(string name, int age) { cout << "Human full " << this << endl; this->name = name; this->age = age; } string GetName() const { return name; } int GetAge() const { return age; } void SetName(const string name) { this->name = name; } void SetAge(const int age) { this->age = age; } }; class Student : public Human { float averageGrade; public: Student() : Human() { cout << "Student default " << this << endl; averageGrade = 0; } Student(string name, int age, float averageGrade) : Human(name, age) { cout << "Student full " << this << endl; this->averageGrade = averageGrade; } float GetAverageGrade() const { return averageGrade; } void SetAverageGrade(float averageGrade) { this->averageGrade = averageGrade; } }; int main() { Student st("Nikita", 21, 10.9); }
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Васильева Ахалия.

Ответ:

#include <iostream>

#include <string>

//set colors(enum)

enum class Color {

   RED,

   BLUE,

   GREEN,

   WHITE,

   BLACK

};

// Create classes and constructors...

class Car {

protected:

   std::string model;

   double speed;

   Color color;

public:

   Car() {

       std::cout << "Car default " << this << std::endl;

       model = "";

       speed = 0.0;

       color = Color::WHITE;

   }

   Car(std::string model, double speed, Color color) {

       std::cout << "Car full " << this << std::endl;

       this->model = model;

       this->speed = speed;

       this->color = color;

   }

   std::string GetModel() const {

       return model;

   }

   double GetSpeed() const {

       return speed;

   }

   Color GetColor() const {

       return color;

   }

   void SetModel(const std::string& model) {

       this->model = model;

   }

   void SetSpeed(double speed) {

       this->speed = speed;

   }

   void SetColor(Color color) {

       this->color = color;

   }

};

class Truck : public Car {

private:

   double cargoVolume;

public:

   Truck() : Car() {

       std::cout << "Truck default " << this << std::endl;

       cargoVolume = 0.0;

   }

   Truck(std::string model, double speed, Color color, double cargoVolume)

       : Car(model, speed, color) {

       std::cout << "Truck full " << this << std::endl;

       this->cargoVolume = cargoVolume;

   }

   double GetCargoVolume() const {

       return cargoVolume;

   }

   void SetCargoVolume(double volume) {

       cargoVolume = volume;

   }

};

//create main function

int main() {

   Car car("Mercedes", 160.0, Color::GREEN); //input case

   Truck truck("Ford", 80.0, Color::BLACK, 1000.0); //input case

   std::cout << "Car model: " << car.GetModel() << ", Speed: " << car.GetSpeed()

             << ", Color: " << static_cast<int>(car.GetColor()) << std::endl;

   std::cout << "Truck model: " << truck.GetModel() << ", Speed: " << truck.GetSpeed()

             << ", Color: " << static_cast<int>(truck.GetColor())

             << ", Cargo Volume: " << truck.GetCargoVolume() << std::endl;

   return 0;

}

0 0
Отвечает Сидоркина Юля.

#include <iostream>

enum class Color {

   RED,

   BLUE,

   GREEN,

   YELLOW

};

class Car {

protected:

   std::string model;

   int speed;

   Color color;

public:

   Car(const std::string& model, int speed, Color color)

       : model(model), speed(speed), color(color) {}

   void display() {

       std::cout << "Model: " << model << std::endl;

       std::cout << "Speed: " << speed << " km/h" << std::endl;

       std::cout << "Color: ";

       switch (color) {

           case Color::RED:

               std::cout << "Red";

               break;

           case Color::BLUE:

               std::cout << "Blue";

               break;

           case Color::GREEN:

               std::cout << "Green";

               break;

           case Color::YELLOW:

               std::cout << "Yellow";

               break;

       }

       std::cout << std::endl;

   }

};

class Truck : public Car {

private:

   int cargoVolume;

public:

   Truck(const std::string& model, int speed, Color color, int cargoVolume)

       : Car(model, speed, color), cargoVolume(cargoVolume) {}

   void display() {

       Car::display();

       std::cout << "Cargo Volume: " << cargoVolume << " cubic meters" << std::endl;

   }

};

int main() {

   Car car("Toyota Camry", 180, Color::BLUE);

   car.display();

   std::cout << "------------------------" << std::endl;

   Truck truck("Volvo FH16", 120, Color::RED, 50);

   truck.display();

   return 0;

}

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Класс "Машина" и класс "Грузовик" сделаны на основе предоставленного кода.

```c++ #include #include

using namespace std;

enum Color { Red, Blue, Green, Yellow };

class Машина { protected: string model; int speed; Color color; public: Машина() { cout << "Машина по умолчанию" << endl; speed = 0; color = Blue; } Машина(string model, int speed, Color color) { cout << "Машина с параметрами" << endl; this->model = model; this->speed = speed; this->color = color; } void setModel(const string& model) { this->model = model; } void setSpeed(int speed) { this->speed = speed; } void setColor(Color color) { this->color = color; } string getModel() const { return model; } int getSpeed() const { return speed; } Color getColor() const { return color; } };

class Грузовик : public Машина { private: int cargoSpace; public: Грузовик() { cout << "Грузовик по умолчанию" << endl; cargoSpace = 0; } Грузовик(string model, int speed, Color color, int cargoSpace) : Машина(model, speed, color) { cout << "Грузовик с параметрами" << endl; this->cargoSpace = cargoSpace; } void setCargoSpace(int cargoSpace) { this->cargoSpace = cargoSpace; } int getCargoSpace() const { return cargoSpace; } };

int main() { Машина car("Toyota", 200, Red); cout << "Марка машины: " << car.getModel() << endl; cout << "Скорость: " << car.getSpeed() << endl; cout << "Цвет: " << car.getColor() << endl; cout << endl;

Грузовик truck("Volvo", 150, Green, 1000); cout << "Марка грузовика: " << truck.getModel() << endl; cout << "Скорость: " << truck.getSpeed() << endl; cout << "Цвет: " << truck.getColor() << endl; cout << "Объем грузового отсека: " << truck.getCargoSpace() << " кг" << endl;

return 0; } ```

В данном коде, класс "Машина" содержит поля модели, скорости и цвета, а также методы для установки и получения значений этих полей. Класс "Грузовик" наследуется от класса "Машина" и добавляет еще одно поле - объем грузового отсека. В данном классе также реализованы методы для установки и получения значения для этого поля.

В функции `main()` созданы объекты классов "Машина" и "Грузовик". Для объектов вызываются соответствующие методы для установки значений полей и методы для получения значений. Затем значения полей выводятся на экран.

Например, после выполнения данного кода будет выводиться:

``` Машина с параметрами Марка машины: Toyota Скорость: 200 Цвет: 0

Машина с параметрами Грузовик с параметрами Марка грузовика: Volvo Скорость: 150 Цвет: 2 Объем грузового отсека: 1000 кг ```

Это значит, что создана "Машина" с моделью "Toyota", скоростью 200 и красным цветом. И "Грузовик" с моделью "Volvo", скоростью 150, зеленым цветом и объемом грузового отсека 1000 кг.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос