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.

  1. 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.
 
#include 

#include

using namespace std;

template

class Car {

private:

T speed;

public:

Car(T speed) { this->speed = speed; }

// getSpeed function will output the speed of the car

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

Car operator+(const Car &aCar);

};

template

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

T sumOfSpeeds;

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

return Car(sumOfSpeeds);

}

int main() {

try {

// Car with numeric values

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

Car c1(20), c2(10);

// Car with string values

// initializing c2 speed with 40 and c4 speed with 50

Car c3("40"), c4("50");

// using + overloading operator on numeric type

Car c5 = c1 + c2;

// using + overloading operator on string type

Car c6 = c3 + c4;

// using + overloading operator on string type (will print error)

// Car c7 = c1 + c3;

c1.getSpeed(); // will print 20

c2.getSpeed(); // will print 10

c3.getSpeed(); // will print 40

c4.getSpeed(); // will print 50

c5.getSpeed(); // will print 30

c6.getSpeed(); // will print 4050

// c7.getSpeed(); // will raise exception

} catch (exception *e) {

// print the exception

cout << "Exception: " << e << endl;

}

return 0;

}

Apparently the coding needs additional templates for constructor, functions for the C++ coding above. Actually the code needed more template functions, like it needs to be listed as inline.

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!