Hi all...
For a project I have to create a small program that adds class data using templates. I've completed the project, but the output is not expected for the last cout in main.
Here is the code:
#include <iostream>
#include<string>
using namespace std;
template <class T>
T add (T x, T y)
{
T summary;
summary = x + y;
return summary;
}
class Homework
{
private:
string className;
string assignment;
int estimatedTime;
public:
friend ostream& operator << (ostream& out, Homework &info);
void setValues(string, string, int);
Homework operator + (Homework &h);
};
ostream& operator<<(ostream& out, Homework &info)
{
out << "Course: " << info.className << endl;
out << "Assignment: " << info.assignment << endl;
out << "Time: " << info.estimatedTime << " minutes" << endl;
out << "--------------------------------------------" << endl;
return (out);
}
void Homework::setValues(string name, string assign, int time)
{
className = name;
assignment = assign;
estimatedTime = time;
}
Homework Homework::operator + (Homework &h)
{
Homework temp;
temp.className = "All Courses";
temp.assignment = "All Assignments";
temp.estimatedTime = h.estimatedTime + h.estimatedTime;
return temp;
}
void userComments()
{
cout << "This program uses a class and overload operators.\n\n" << endl;
}
int main()
{
int a = 65, b = 90, c, num;
double d = 45.25, e = 120.5, f;
Homework h, i, j;
h.setValues("English","Read Chapter 11", 75);
i.setValues("History","Read Chapter 22", 45);
c = add (a,b);
f = add (d,e);
j = add (h,i);
userComments();
cout << "Result of integer addition: " << c << endl;
cout << "Result of double addition: " << f << endl;
cout << "Result of homework addition: " << j << endl;
cout << "Press 1 to exit";
cin >> num;
while(num != 1)
{
cout << "Must press 1 to exit program - please enter 1: ";
cin >> num;
}
}
I don't understand what is happening to h when it is sent to the overloaded >> operator...seems like it is just going "poof" and only i is being added in the template.
Thanks in advance for any pointers you can/will give me.
Jason