In the first example, fstream works with operator << as expected.
The second example is similar, but with the fstream in a wrapper.
How to make it work with the operator <<?
My failed attempt to overload << is in the second example.
#include <stdlib.h>
#include <iostream>
#include <fstream>
int main()
{
charconst* fileName="file1.txt";
std::fstream of;
of.open(fileName);
if (of.is_open())
{
std::cerr << fileName << " opened for writing.\n";
}
else
{
std::cerr << fileName << " could not be opened for writing!\n";
exit(0);
}
of << "hello"; //'hello' appears in file1.txt
}
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <istream>
class OutFile
{
private:
std::fstream outf;
public:
void initialize(charconst* fileName);
};
void OutFile::initialize(charconst* fileName)
{
outf.open(fileName);
if (outf.is_open())
{
std::cerr << fileName << " opened for writing.\n";
return;
}
std::cerr << fileName << " could not be opened for writing!\n";
exit(0);
}
//overload <<
OutFile& operator<<(OutFile& outf, std::istream& in)
{
outf << in;
return outf;
}
int main()
{
charconst* fileName="file2.txt";
OutFile of;
of.initialize(fileName);
of << "hello"; //compiles and runs when this line is commented
}
example 2 output:
C:\Users\wolf\Documents\demo_MinGW\OutFile>g++ main.c
main.c: In function 'int main()':
main.c:40:5: error: no match for 'operator<<' (operand types are 'OutFile' and '
const char [6]')
of << "hello"; //compiles and runs when this line is commented
^
main.c:40:5: note: candidate is:
main.c:28:10: note: OutFile& operator<<(OutFile&, std::istream&)
OutFile& operator<<(OutFile& outf, std::istream& in)
^
main.c:28:10: note: no known conversion for argument 2 from 'const char [6]' t
o 'std::istream& {aka std::basic_istream<char>&}'
Maybe example 2 is not the best way to write the OutFile class.
Would it be better to use a wrapper or inherit from fstream?