0

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.

  • In the header file, specify the argument of `Display()` with type `std::ofstream &`. Don't rely on `using namespace std` being in effect. Also, look up the use of include guards. – Peter Mar 28 '18 at 10:17

1 Answers1

5

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)

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42
  • 2
    [Why is “using namespace std” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Yksisarvinen Mar 28 '18 at 09:32