user2044504
user2044504

Reputation:

friend overloaded operator without namespace std

Just wondering if anyone could point me in the right direction. I have a friend extraction operator that works if i include namespace std; but fails if i do not. can anyone give me a hint?

ostream& operator << (ostream &out, coins &value)

this is also a friend function, so i have this in my class.h file (as a friend) in my functions.h file (as the prototype) and in my functions.cpp file (the logic).

ive tried making it

std::ostream& operator.... std::ostream& operator std::<< (etc)

but i just cant see where im going wrong. My compiler keeps telling me 'ostream does not name a type'

thank you

Upvotes: 1

Views: 1039

Answers (1)

GManNickG
GManNickG

Reputation: 503973

It's ostream that exists in the std namespace, don't do std::<< (that doesn't even make sense!). Try to take less of a shotgun approach to programming; that is, don't just try random things until it works. The error tells you ostream (unqualified) is the problem, so you have to solve that issue first.

#include <iostream>

struct coins
{
    friend std::ostream& operator<<(std::ostream& sink, const coins& value);
};

std::ostream& operator<<(std::ostream& sink, const coins& value)
{
    sink << "doing coins output";
    return sink;
}

int main()
{
    coins c;
    std::cout << c << std::endl;
}

This is an insertion operator, by the way, as you're inserting data to a stream. Extraction would be >>.

Upvotes: 2

Related Questions