I have to overload the shift operator " << " both for writing in console and to write on a binary file..
I am doing okay for the ostream overloading, while I am having some problem overloading the fstream, here it is:
in my header:
friend ostream &operator<<(ostream &, const Fotografia &);
friend fstream &operator<<(fstream &, const Fotografia &);
in my cpp file:
fstream &operator<<(fstream & miofile, const Fotografia & sorgente)
{
//Open the file
miofile.open("data.dat", ios::binary | ios::app);
if(!miofile) cerr << "Can't open the file\n";
miofile << strlen(sorgente.Titolo);
miofile << endl;
miofile << sorgente.Titolo;
//I close the file
miofile.close();
return miofile;
}
Here's the error I am facing:
In function `std::fstream& operator<<(std::fstream&, const Fotografia&)':
ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const char*) [with _Traits = std::char_traits<char>]
std::fstream& operator<<(std::fstream&, const Fotografia&)
What I understood so far is that there's ambiguosity between the overloaded function I just created and the standard fstream << . Now, what I do not understand is why, because my overloaded function should work just for the class "Fotografia" (which was created by me), while I am trying to write a char * .
I thought I could solve this problem by calling the fstream operator with the "::" scope but I am not sure.
Could anyone help me out here please? :)
EDIT:
I am posting the code for the header and the code for the constructor
//Costruttore,distruttore,costruttore di copia,operatore di assegnazione.
Fotografia(char * titolo = "Untitled" , char * formato = ".jpeg");
~Fotografia() { delete [] Titolo; delete [] Formato;}
Fotografia(const Fotografia &);
Fotografia &operator=(const Fotografia &);
This is in the cpp:
Fotografia::Fotografia(char * titolo , char * formato)
{
Titolo = new char[strlen(titolo)+1];
strcpy(Titolo,titolo);
Formato = new char[strlen(formato)+1];
strcpy(Formato,formato);
} //Fine costruttore
fstream
is anostream
. – Muscovitefstream
passed intooperator<<
be opened and closed by the caller? as it is passing it in and out of the function is kind of pointless. About your problem: Do you have any implicit conversions betweenchar*
andFotografia
(operator char*
orFotografia(const char*)
)? – Trichinosis