To solve the garbage problem: give the parameters of the constructor other names than the data itself, for example:
cpp
RacingData::RacingData(string new_racerName, int new_score, int new_minutes, int new_seconds)
{
racerName = new_racerName;
score = new_score;
minutes = new_minutes;
seconds = new_seconds;
}
To solve the problems with the minutes/seconds: you can do a check:
cpp
if (seconds >= 60)
{
minutes += seconds / 60;
seconds = seconds % 60;
}
For the operator overloading, I have added it to your class. There the adjusted code:
cpp
#include <iostream>
#include <string>
using namespace std;
int dpAvg;
int jgAvg;
int dpTotal;
int jgTotal;
class RacingData
{
public:
RacingData(string,int,int,int); //constructor with parameters
RacingData(); // default constructor
RacingData operator+(const RacingData& a); // overloaded operator +
void printRacingData(); //displays race results
int score, minutes, seconds;
string racerName;
};
RacingData::RacingData(string new_racerName, int new_score, int new_minutes, int new_seconds)
{
racerName = new_racerName;
score = new_score;
minutes = new_minutes;
seconds = new_seconds;
}
RacingData::RacingData()
{
racerName = " ";
score = 0;
minutes = 0;
seconds = 0;
}
void RacingData::printRacingData()
{
cout << racerName << " " << score << " " << minutes << ":" << seconds << "\n";
}
/**
Operator + for the class RacingData
*/
RacingData RacingData::operator+(const RacingData& a)
{
RacingData res = RacingData();
// copy name but only if both names are identical
if (racerName == a.racerName)
{
res.racerName = racerName;
}
// add up all data elements
res.score = score + a.score;
res.minutes = minutes + a.minutes;
res.seconds = seconds + a.seconds;
// reduce seconds to below 60
if (res.seconds >= 60)
{
res.minutes += res.seconds / 60;
res.seconds = res.seconds % 60;
}
return res;
}
int main()
{
RacingData dpRace1("Danica Patrick", 185, 11, 20);
RacingData dpRace2("Danica Patrick", 103, 11, 30);
RacingData dpRace3("Danica Patrick", 73, 12 ,40);
RacingData jgRace1("Jeff Gordon", 155, 10, 10);
RacingData jgRace2("Jeff Gordon", 127, 11, 15);
RacingData jgRace3("Jeff Gordon", 34, 12, 35);
cout << "Race Results\n";
dpRace1.printRacingData();
dpRace2.printRacingData();
dpRace3.printRacingData();
jgRace1.printRacingData();
jgRace2.printRacingData();
jgRace3.printRacingData();
cout << "Total Scores:\n";
RacingData dpTotal = dpRace1 + dpRace2 + dpRace3;
RacingData jgTotal = jgRace1 + jgRace2 + jgRace3;
dpTotal.printRacingData();
jgTotal.printRacingData();
system("PAUSE");
return 0;
}
This post has been edited by joske: 1 Jun, 2008 - 11:41 AM