saigafreak
saigafreak

Reputation: 415

Migrating C++ code to use standard headers. Now getting: reference to 'ostream' ambiguous

I've been migrating some code to alter the declarations of headers, since they're not included in my Ubuntu environment. I've finally changed all of the files but have been getting the following error:

Item.h:33: error: reference to ‘ostream’ is ambiguous
Item.h:16: error: candidates are: struct ostream
/usr/include/c++/4.4/iosfwd:130: error:                 typedef struct  
std::basic_ostream<char, std::char_traits<char> > std::ostream 
Item.h:33: error: ISO C++ forbids declaration of ‘ostream’ with no type
Item.h:33: error: ‘ostream’ is neither function nor member function; cannot be declared friend

Code is as follows:

class Item
{
public:
    Item( //const Wrd* hd,
     const Term * _term, int _start, int _finish );
    ~Item();
    int         operator== (const Item& item) const;
    friend ostream& operator<< ( ostream& os, const Item& item ); // <-- error

Anyone know how I would rectify this?

Upvotes: 0

Views: 3805

Answers (3)

templatetypedef
templatetypedef

Reputation: 373042

It looks like in Item.h you have a line that looks like this:

struct ostream;

The problem you're getting is that ostream is not a struct; it's a typedef for basic_ostream<char>, and so your custom definition of ostream is conflicting with the standard definition of ostream that's forward-declared in <iosfwd>. Consequently, when you write

friend ostream& operator<< ( ostream& os, const Item& item );

The compiler can't tell if ostream refers to your struct ostream or the more complex typedef exported by the standard header file.

To fix this, find the spot where you've tried to forward-declare ostream and remove it. Instead, consider using the header file <iosfwd> to import a forward-reference to ostream.

More generally, you shouldn't try forward-declaring anything in the standard library. Just #include the appropriate header for it.

Upvotes: 5

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133092

The comppiler tells you exactly what's going on:

there is a typedef for a template specialization ( basic_ostream<char...>) named ostream (which obviously comes from the standard header) and there is a struct ostream defined somewhere else in your code(which you must seek to find and rename/ramove). Hence the ambiguity

Upvotes: 1

D.Shawley
D.Shawley

Reputation: 59613

Have you tried friend std::ostream& operator<< ...? It is hard to answer without seeing the rest of the header.

Upvotes: 0

Related Questions