stream pointer in a class

G

Gary Wessle

Hi

I am trying to establish an output stream pointer to append things to
a file as follows, is this correct?

thanks


class A{
ofstream ofs;
public:
A();
};

A::A(){
ofs.open("trying.txt", ios::app);
}

class B{
A* a;
public:
B(A* a) : a(a)
{
myMeth();
}
void myMeth(){
a->ofs << "stream pointer output" << endl;
}
};

int main(){
A a;
B(&a);
}
 
?

=?ISO-8859-1?Q?Erik_Wikstr=F6m?=

Hi

I am trying to establish an output stream pointer to append things to
a file as follows, is this correct?

thanks


class A{
ofstream ofs;
public:
A();
};

A::A(){
ofs.open("trying.txt", ios::app);
}

class B{
A* a;
public:
B(A* a) : a(a)
{
myMeth();
}
void myMeth(){
a->ofs << "stream pointer output" << endl;

a->ofs is private and you can't access it from B.
}
};

int main(){
A a;
B(&a);
}

Why create a wrapper around the ofstream? Would it not have been easier
to just keep a reference like the following?

class B{
std::eek:fstream& ofs;
public:
B(std::eek:fstream& o) : ofs(o) {
myMeth();
}
void myMeth() {
ofs << "stream reference output" << std::endl;
}
};

int main() {
B( std::eek:fstream("trying.txt", std::ios::app) );
return 0;
}

Or, if you must, keep a pointer to it, but wrapping it in a class serves
no purpose so far.
 

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

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,266
Latest member
DavidaAlla

Latest Threads

Top