Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Write C++ code to modify your Car class from assignment 5 (with the overloaded operators) to use templates. Add a constructor that allows you to

  1. Write C++ code to modify your Car class from assignment 5 (with the overloaded operators) to use templates. Add a constructor that allows you to initialize your speed member variable, so it is no longer restricted to int, float, etc.

#include

using namespace std;

class Car {

private:

int speed;

public:

Car(int speed = 0) { this->speed = speed; }

// virtual void accelerate();

// virtual void stop();

// virtual void getSpeed() const;

// getSpeed function will output the speed of the car

void getSpeed() const { cout << "speed : " << this->speed << " "; }

Car operator-(const Car &aCar);

Car operator+(const Car &aCar);

};

Car Car::operator+(const Car &aCar) {

int sumOfSpeeds;

sumOfSpeeds = (this->speed + aCar.speed);

return Car(sumOfSpeeds);

}

Car Car::operator-(const Car &aCar) {

int difference;

difference = (this->speed - aCar.speed);

return Car(difference);

}

int main() {

// initializing c1 speed with 20 and c2 speed with 10

Car c1(20), c2(10);

// using + overloading operator

Car c3 = c1 + c2;

// using - overloading operator

Car c4 = c1 - c2;

c1.getSpeed(); // will print 20

c2.getSpeed(); // will print 10

c3.getSpeed(); // will print 30

c4.getSpeed(); // will print 10

return 0;

}

Apparently the code needs additional templates for constructor and functions for the C++ coding.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Design Application Development And Administration

Authors: Mannino Michael

5th Edition

0983332401, 978-0983332404

More Books

Students also viewed these Databases questions