Question: 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

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.

Here is the Assignment 5 coding:

#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); cout << sumOfSpeeds << endl; return sumOfSpeeds; }

Car Car::operator - (const Car & aCar) { int difference; difference = (this -> speed - aCar.speed); cout << difference << endl; return 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; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!