开发者

unrecognized type in a function call

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 in开发者_开发问答clude the file in the right way.


Use std::ofstream

This is because we have to explicitly specify which ofstream we are talking about. Since the standard namespace std contains the name ofstream, it has to be explicitly told to the compiler

There 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

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


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.

#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);
}


the problem was with the order of the included "h" files i didnt include in the right order after fixing it all worked perfectly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜