函数调用中无法识别的类型
我正在尝试用 C++ 打印到一个文件中,由于某种原因,我不断收到这个奇怪的错误:
错误 C2061:语法错误:标识符 'ofstream'
我包含以下内容:
#include <fstream>
#include <iostream>
这是我的函数:
void Date::PrintDate(ofstream& resultFile) const
{
resultFile << m_day << "/" << m_month << "/" << m_year;
}
我正在使用命名空间 std
。
我想通了,这都是因为我没有以正确的方式包含该文件。
I am trying to print into a file in C++ and for some reason I keep getting this weird error:
error C2061: syntax error : identifier
'ofstream'
I included the following:
#include <fstream>
#include <iostream>
This is my function:
void Date::PrintDate(ofstream& resultFile) const
{
resultFile << m_day << "/" << m_month << "/" << m_year;
}
I am using namespace std
.
I figured it out, it was all because I did not include the file in the right way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 std::ofstream
这是因为我们必须明确指定我们正在谈论哪个 ofstream。由于标准命名空间
std
包含名称ofstream
,因此必须显式告知编译器。本质上有两种方法:
在 .cpp 文件中的所有包含文件之前,有一个 using 指令
1:
using namespace std;
或
2:在命名空间 std 中的每个名称前添加
std::
编辑 2:
修改后的函数声明应如下所示因为选项 1(上面)是避免全局命名空间污染的首选方法通常
Use
std::ofstream
This is because we have to explicitly specify which ofstream we are talking about. Since the standard namespace
std
contains the nameofstream
, it has to be explicitly told to the compilerThere are essentially two ways:
Just before all the include files in the .cpp file, have a using directive
1:
using namespace std;
or
2: prefix each name from the namespace std with
std::
EDIT 2:
Your revised function declaration should look as follows as Option 1 (from above) is a preferred way to avoid global namespace pollution usually
我以为我疯了,我尝试编译一个修改/简化的版本,它工作得很好。您确定使用的是 C++ 编译器而不是 C 编译器吗?例如 g++ 而不是 gcc。
Thinking I was going insane, I tried compiling a modified/simplified version, and it works fine. Are you sure you're using a C++ compiler and not a C compiler? e.g. g++ instead of gcc.
问题在于所包含的“h”文件的顺序,在修复所有文件后,我没有以正确的顺序包含它。
the problem was with the order of the included "h" files i didnt include in the right order after fixing it all worked perfectly.