Hi i am new to C++ and i am working on a project where i override the output operater << using a friend method i know how to do this for a regular output where cout << is used however my teacher has provided a main method for me to test my results on and he does not use cout he uses output from ofstream which i dont quite understand a more abstract simpler example of what i am dealing with is posted below:
#include <iostream>
usingnamespace std;
class Date
{
int mo, da, yr;
public:
Date(int m, int d, int y)
{
mo = m; da = d; yr = y;
}
friend ostream& operator<<(ostream& out, Date& dt);
// friend method to ovveride output
};
// implementation of friend method
ostream& operator<<(ostream& out, Date& dt)
{
out << dt.mo << '/' << dt.da << '/' << dt.yr;
return out;
}
int main()
{
Date dt(5, 6, 92);
cout << dt; // cout is overiden and this works
}
OutPuts the date like 5/6/92
Now using my teachers main method provided
This Doesnt Work:
#include <iostream>
#include <fstream> // fstream is included
usingnamespace std;
class Date
{
int mo, da, yr;
public:
Date(int m, int d, int y)
{
mo = m; da = d; yr = y;
}
friend ostream& operator<<(ostream& out, Date& dt); // same friend method
};
// same implementation
ostream& operator<<(ostream& out, Date& dt)
{
out << dt.mo << '/' << dt.da << '/' << dt.yr;
return out;
}
// my teachers main
int main()
{
ofstream output("output",ios::out); // this used instead of cout?
if (output == NULL)
{
cerr << "File cannot be opened" << endl;
exit(0);
}
Date dt(5, 6, 92);
output << dt; // absolutly nothing is output "press any key to continue"
}
Please could someone explain why this isnt working for my teachers main method but it does for mine? and how can i fix this so i get the same output for both.
Thank You i hope i have explained everything well enough please just ask if you need clarification
Even better than making that a friend would be to have getter methods to return copies of the month, day, and year so you can use them in your overload.
Friend functions work but they can compromise you class's integrity because now the client has full access to your private data that function.