Andrei Trasca
Andrei Trasca

Reputation: 39

ofstream as a method argument in c++

I need some help. I know that you can have a function like this

void foo (std::ofstream& dumFile) {}

But I have a class in which I want to do the same thing and the compiler gives me tons of errors.

My main.cpp file looks like this:

#include <iostream>
#include <fstream>
#include "Robot.h"
using namespace std;

ofstream fout("output.txt");

int main() {
    Robot smth;
    smth.Display(fout);
    return 0;
}

And my Robot.h would look something like this:

#include <fstream>
class Robot{
private:
     int smth;
public:
     void Display(ofstream& fout) {
         fout << "GET ";
     }
};

Now if I try to compile this I'll get this errors:

error: ‘ofstream’ has not been declared
 error: invalid operands of types ‘int’ and ‘const char [5]’ to binary ‘operator<<’

Any help is really appreciated.

Upvotes: 0

Views: 807

Answers (1)

Yury Schkatula
Yury Schkatula

Reputation: 5369

You really have to respect namespaces :)

class Robot{
private:
     int smth;
public:
     void Display(std::ofstream& fout) {
         fout << "GET ";
     }
};

Your main file has using namespace std; and your Robot.h file has not. (and this is good, because it's quite dangerous idea to have "using namespace" construct inside a header file)

Upvotes: 5

Related Questions