Search code examples
c++operator-overloadingoperatorsostream

operator << overloading for vector of objects


everybody.

I have a class called "Card" and "CardDeck" where the second is a vector, which contains many cards of the first class.

My << overloading goes like this:

istream& operator<<(ostream& os, Card& card) {
    string str;
    if(cardValueCorrect(card._value)){
        str += to_string(card._value);
    } else {
        str += card._identier;
    }
    str += suitToChar(card._suit);
    return os << str;

And that I think should be fine, at least the compiler doesnt complain about this. The trouble starts when in my CardDeck I want to overload << so it would print all the cards are in.

CardDeck << overloading seems like that: 
ostream& operator<<(ostream& os, CardDeck& odeck){
    for(const Card cur_card: odeck._Deck){
        os << cur_card << ' ';
    }
    return os;
}

It complains about accessing to private fields of card and also:

invalid initialization of reference of type 'std::istream& {aka std::basic_istream<char>&}' from expression of type 'std::basic_ostream<char>'

and then other very strange stuff as (about each line in the first operator overloading):

within this context

EDIT

istream to ostream fixed.

That was one probem. Now I see 162 warrnings with "info" about the CardDeck operator overloading and it tell's me i'm getting to private fields of CardDeck (the vector is there).

Eather:

`invalid initialization of non-const reference of type 'CardDeck&' from an rvalue of type no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'const Card')` 

and a lot of "info" (eclipse) of such repeating pattern:

'const Card' is not derived from 'const std::extreme_value_distribution<_RealType>'

Solution

  • Replace

    istream& operator<<(ostream& os, Card& card)
    

    with

    ostream& operator<<(ostream& os, Card& card)