Question
Write C++ code for a main function that creates instances of the template version of your Car class you just wrote within a trycatch statement.
Write C++ code for a main function that creates instances of the template version of your Car class you just wrote within a trycatch statement. Create four cars. Two of them should set speed to a numeric value and two should use strings for speed. Overload the + operator on them by adding the Cars with numeric speed, adding the Cars with strings for speed, and adding one Car with a string and another with a number for speed.
Here is the code that was just written:
#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;
}
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