RootAtShell
RootAtShell

Reputation: 115

Overloading ofstream produces two different results

I have overloaded the ofstream operator in one particular file, cfileop.cpp, as such:

std::ostream& operator<<(std::ostream& ofs, LPCWSTR wideString)
{
    //ofs << ConvertUnicodeToUtf8(wideString).GetBuffer();
    ofs << CW2A(wideString,CP_UTF8);
    return ofs;
}

In this particular file, any call being made using the operator works perfect. I have no problems at all.

However, I need to overload this same operator in another file. When I repeat this call in another location, acrazyapp.cpp, I get something like this output:

02962AE010021A3402961018
029621C010021A3410022AF0
029621C010021A34029619D0
029621C010021A3410022A68

Which, I thought, could be solved simply by switching the location of the overload to acrazyapp.cpp. This, however, caused cfileop.cpp not to properly output. In an attempt to satisfy both, I moved the call to a header file, ch_ofstream.h, and included it in both cpp files. However, in this case, I received this error: fatal error LNK1169: one or more multiply defined symbols found.

How can I ensure that the ofstream operator above is properly overloaded in both cpp files without combining the cpp files?

Thank you!

Upvotes: 0

Views: 258

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52601

Since the overload is not declared in that other file, you end up calling operator<<(void*), which prints the address that the pointer points to.

As with any other function, you should declare it in one header file, and implement in one source file.

Upvotes: 1

Related Questions