ofstream作为c ++中的方法参数

And*_*sca 0 c++ fstream ofstream

我需要一些帮助.我知道你可以拥有这样的功能

void foo (std::ofstream& dumFile) {}
Run Code Online (Sandbox Code Playgroud)

但我有一个类,我想做同样的事情,编译器给了我很多错误.

我的main.cpp文件如下所示:

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

ofstream fout("output.txt");

int main() {
    Robot smth;
    smth.Display(fout);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的Robot.h看起来像这样:

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

现在,如果我尝试编译这个,我会得到这个错误:

error: ‘ofstream’ has not been declared
 error: invalid operands of types ‘int’ and ‘const char [5]’ to binary ‘operator<<’
Run Code Online (Sandbox Code Playgroud)

任何帮助都非常感谢.

Yur*_*ula 5

你真的必须尊重命名空间:)

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

你的主文件有using namespace std;,你的Robot.h文件没有.(这很好,因为在头文件中使用"using namespace"构造是非常危险的)

  • [为什么"使用命名空间标准"被认为是不好的做法?](/sf/ask/101690501/) (2认同)