函数调用中无法识别的类型

时间:2010-09-05 16:21:12

标签: c++ fstream

我正在尝试使用C ++打印到一个文件中,出于某种原因我不断收到这个奇怪的错误:

  

错误C2061:语法错误:标识符   '的ofstream'

我包括以下内容:

#include <fstream>
#include <iostream>

这是我的功能:

void Date::PrintDate(ofstream& resultFile) const
{
    resultFile << m_day << "/" << m_month << "/" << m_year;
}

我是using namespace std


我想通了,这完全是因为我没有以正确的方式包含文件。

3 个答案:

答案 0 :(得分:3)

使用std::ofstream

这是因为我们必须明确指出我们正在谈论的流。由于标准名称空间std包含名称ofstream,因此必须将其明确告知编译器

基本上有两种方式:

在.cpp文件中的所有包含文件之前,有一个using指令

1:using namespace std;

2:使用std::

为名称空间std中的每个名称添加前缀

编辑2:

您修改后的函数声明应如下所示,因为选项1(来自上面)是避免全局命名空间污染的首选方法通常

void Date::PrintDate(std::ofstream& resultFile) const 
{ 
    resultFile << m_day << "/" << m_month << "/" << m_year; 
} 

答案 1 :(得分:0)

以为我疯了,我尝试编译修改/简化版本,它运行正常。您确定使用的是C ++编译器而不是C编译器吗?例如g ++而不是gcc。

#include <iostream>
#include <fstream>

using namespace std;

void printDate(ofstream& resultFile)
{
resultFile << 1 << "/" << 1 << "/" << 2010;
}

int main(int arg, char **argv)
{
ofstream ofs("ADate.txt");
if (!ofs) cerr << "huh?";
printDate(ofs);
}

答案 2 :(得分:0)

问题在于所包含的“h”文件的顺序,在修复完所有工作后,我没有按照正确的顺序包含这些文件。