Why don't you just take the reference of the stream, such as
ostream &l = Utils::theLog;
l << "Hello, World!\n";
In this way, you don't have to use pointers.
Question
So I've been fooling around with statics, pointers and typedefs and I've run into a brick wall and was wondering if someone could offer some insight.
I have a class Utils
with a static ofstream
called theLog
and I have another class Work
that makes use of Utils::theLog
. Here's the pertinent code:
#ifndef UTILS_H
#define UTILS_H
// includes
class Utils {
public:
static ofstream theLog;
// other code
}
#endif
// includes
typedef ofstream* pOfStream;
static pOfStream l = &(Utils::theLog); // l is a lowercase L
// constructor and destructor
void Work::doSomeWork() {
(*l) << "Hello, world!\n";
}
// other code
This compiles and gives no runtime errors. However the reason for defining pOfStream
was to eliminate the filling of my code with asterisks, parentheses and Utils::theLog
. When I try replacing (*l)
with just l
as in: l << "Hello, world!\n";
I get compiler errors. I'm assuming the reason being is that the operator <<
takes precedence over *
, even though l
is of the type pOfStream
, which is defined as being a pointer to an ofstream
object, however the code is not implicitly written *l << "Hello, world!\n";
.
My question being, is there a way to use the extraction operator <<
without having to surround a pointer with parentheses and an asterisk? Also when you define a type like the above pOfStream
and then assign a variable var
to the type pOfStream
, does the compiler just read through the code and replace any instance of pOfStream
with ofstream*
?
I've been searching SO and Google for the answer but I'm not exactly sure how to phrase the question.
La solution
Why don't you just take the reference of the stream, such as
ostream &l = Utils::theLog;
l << "Hello, World!\n";
In this way, you don't have to use pointers.