Insertion operator onto object

C

cpp

Ok, I have been tearing my hair out trying to get this to work, so anything you
can do I will greatly appreciate. I have this small class which is supposed to
make, for its users, outputting to a file easy:
-----------------------------------
class Out {
private:
const char *path;
ofstream outfile;
public:
Out(const char *c);
Out(const string &s);
~Out();
void close();
};

Out::Out(const char *c)
{
path = c;
ofs.open(path);
}
Out::Out(const string &s)
{
path = s.c_str();
ofs.open(path);
}
Out::~Out()
{
delete path;
}
void Out::close()
{
ofs.close();
}
-----------------------------------

As you can see, the Out class has an ofstream member variable associated with
it. Now what I want to do is overload the insertion operator << so that I can
use it on an Out object, and have the effect of inserting into Out's ofstream
variable.

int main()
{
Out *myout = new Out("test.txt");
*myout << "This is a number" << 5;
myout->close();
return 0;
}

How do I define an operator function so that: *myout << "This is a number";

should do the following? : myout->outfile << "This is a number" << 5;

Thanks a million.
 
J

Jonathan Turkanis

cpp said:
Ok, I have been tearing my hair out trying to get this to work, so anything you
can do I will greatly appreciate. I have this small class which is supposed to
make, for its users, outputting to a file easy:

The standard already provides such a class: ofstream. (Okay, a
typedef.)
-----------------------------------
class Out {
private:
const char *path;
ofstream outfile;
public:
Out(const char *c);
Out(const string &s);
~Out();
void close();
};

Out::Out(const char *c)
{
path = c;
ofs.open(path);
}
Out::Out(const string &s)
{
path = s.c_str();
ofs.open(path);
}

These constructors are dangerous -- how long will the const char* used
to initialize path remain valid? Store a std::string instead.
How do I define an operator function so that: *myout << "This is a
number";

See the recent thread "Subclassing to get << and >>". Summary: it's a
waste of time to implement all the overloads of << -- that's what
standard streams are for.

Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,432
Latest member
GTRNorbert

Latest Threads

Top