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.
#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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started