Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friend methods error

Tags:

c++

I get this error message:

'friend' used outside of class.

My header has this line

private:
        friend ostream& operator << (ostream&, card&);

and in the cpp file it is

friend ostream& operator << (ostream& outStream, card& card)
{
    Suit suit=card.getSuit();
    Rank rank=card.getRank();
    string str;
    switch(rank)
        { /*...*/ }
    outStream<<str;
    return outStream;

like this.

I searched but mostly it says that I need same class without friend but I tried, and it did not work. Can you please give me some suggestion?

Thank you

like image 547
user3458856 Avatar asked Dec 15 '22 23:12

user3458856


1 Answers

Remove the friend in the .cpp file. It is only required (and allowed) within the class definition in the header file.

In the header file, you declare that the operator is your friend:

private:
    friend ostream& operator << (ostream&, card&);

This is a property of the class.

In the source file, just define the operator "normally":

ostream& operator << (ostream& outStream, card& card)
{
    // ...
}

Here, friend does not make sense: Friend of whom? Multiple classes might declare the operator as friend.

like image 77
Ferdinand Beyer Avatar answered Jan 27 '23 13:01

Ferdinand Beyer