How to make an ofstream object global so that all class functions can access it?
The example below is my failed attempt.
Passing an instance of type ostream& to func() is not an option, because there will be an intermediary function between main() and func() that I can not change.
#include <fstream>
#include <iostream>
#include "A.h"
std::ofstream result("result.txt\0");
int main()
{
A a;
result << "test1";
a.func();
}
A.h:
1 2 3 4 5 6 7 8 9 10
#ifndef A_h
#define A_h
#include <fstream>
class A
{
public:
void func() { result << "test1"; }
};
#endif
A.cpp:
1 2 3
#include "A.h"
A::void func() { result << "test1"; }
output:
D:\wolf\Documents\teensy\demo_MinGW\stream>make
g++ -Wall main1.cpp -o obj/main1.o
In file included from main1.cpp:3:0:
A.h: In member function 'void A::func()':
A.h:8:17: error: 'result' was not declared in this scope
void func() { result << "test1"; }
^
make: *** [obj/main1.o] Error 1
First, why do you need to make it global? You can pass it through a constructor, or even as part of the function arguments: (EDIT: Read your question again)
1 2 3 4 5 6 7 8
class A {
public:
A(std::ofstream& out) : _out(out) {}
void func(std::ofstream& out) {out << "Hi!"; }private:
std::ofstream& out;
};
Also, in your A.cpp file, you are redefining func. Take your definition out of the header file. In addition, you have some wierd syntax for defining the function, its more normally like this:
void A::func(...) {...}
Anyway, as to your question, the same way you make anything global: You declare it as existing outside of the file. Here is how: