[ale] Q: directing stream I/O _the_C++_way_
Joe Knapka
jknapka at kneuro.net
Sun Nov 28 01:30:15 EST 2004
Hi John,
Your code is failing due to the semantics of references.
(1) References must always be initialized when declared, and
(2) Assigning to a reference is exactly the same as assigning to the
referenced object; since ostreams aren't assignable (operator== is
private), assigning to a reference to an ostream won't work either.
You can use pointers, but it's ugly:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
ostream* out = &cout;
if (argc>1) {
out = new fstream(argv[1]);
}
ostream& ref_out = *out;
ref_out << "Hello, world!" << endl;
if (out != &cout) delete out; // Ick-a-rama...
}
Cheers,
-- Joe
John Mills <johnmills at speakeasy.net> writes:
> Fletch --
>
>
> On Sat, 27 Nov 2004, Fletch wrote:
>
> > I want to say that you should be able to declare an ostream and assign
> > either an ofstream or cout as desired.
> >
> > ostream& log; <-------[initializing to 'cout' => same whine]-----+
> > |
> > if( logfilename ) { |
> > ofstream logfile( logfilename.c_str() ); |
> > log = logfile; |
> ^^^^^^^^^^^^^---- This doesn't compile. I get: |
> V
> Switchbox.cpp:38: `logging' declared as reference but not initialized
> /usr/include/c++/3.2.3/bits/ios_base.h: In member function
> `std::basic_ios<char, std::char_traits<char> >& std::basic_ios<char,
> std::char_traits<char> >::operator=(const std::basic_ios<char,
> std::char_traits<char> >&)':
> /usr/include/c++/3.2.3/bits/ios_base.h:427: `std::ios_base&
> std::ios_base::operator=(const std::ios_base&)' is private
> Switchbox.cpp:133: within this context
> make: *** [Switchbox.o] Error 1
>
> > } else {
> > log = cout;
> > }
>
> - John Mills
> john.m.mills at alum.mit.edu
>
> _______________________________________________
> Ale mailing list
> Ale at ale.org
> http://www.ale.org/mailman/listinfo/ale
>
>
--
"Meet the new boss / Same as the old boss..." -- The Who
... Oh well, at least there's 2008.
--
pub 1024D/BA496D2B 2004-05-14 Joseph A Knapka
Key fingerprint = 3BA2 FE72 3CBA D4C2 21E4 C9B4 3230 94D7 BA49 6D2B
If you really want to get my attention, send mail to
jknapka .at. kneuro .dot. net.
More information about the Ale
mailing list