ofstream 作为 C++ 中的方法参数
ofstream as a method argument in c++
我需要一些帮助。我知道你可以有这样的功能
void foo (std::ofstream& dumFile) {}
但是我有一个 class,我想在其中做同样的事情,但编译器给我很多错误。
我的 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;
}
我的 Robot.h 看起来像这样:
#include <fstream>
class Robot{
private:
int smth;
public:
void Display(ofstream& fout) {
fout << "GET ";
}
};
现在如果我尝试编译它,我会得到这个错误:
error: ‘ofstream’ has not been declared
error: invalid operands of types ‘int’ and ‘const char [5]’ to binary ‘operator<<’
非常感谢任何帮助。
你真的必须尊重命名空间:)
class Robot{
private:
int smth;
public:
void Display(std::ofstream& fout) {
fout << "GET ";
}
};
您的主文件有 using namespace std;
而您的 Robot.h
文件没有。 (这很好,因为在头文件中构建 "using namespace" 是非常危险的想法)
我需要一些帮助。我知道你可以有这样的功能
void foo (std::ofstream& dumFile) {}
但是我有一个 class,我想在其中做同样的事情,但编译器给我很多错误。
我的 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;
}
我的 Robot.h 看起来像这样:
#include <fstream>
class Robot{
private:
int smth;
public:
void Display(ofstream& fout) {
fout << "GET ";
}
};
现在如果我尝试编译它,我会得到这个错误:
error: ‘ofstream’ has not been declared
error: invalid operands of types ‘int’ and ‘const char [5]’ to binary ‘operator<<’
非常感谢任何帮助。
你真的必须尊重命名空间:)
class Robot{
private:
int smth;
public:
void Display(std::ofstream& fout) {
fout << "GET ";
}
};
您的主文件有 using namespace std;
而您的 Robot.h
文件没有。 (这很好,因为在头文件中构建 "using namespace" 是非常危险的想法)