0

I'm new to coding, but basically my assignment is to play the card game war and overloading operators to do so. So my question is how to overload the insertion operator when it is a class member function (the assignment says it must be).

My class is as follows:

class Card{
    private:
        char value; 
        char suit; 
    public:
        Card(){}
        ofstream& operator << (ofstream& COUT)const{
            COUT << value << suit;
            return COUT;
        }

I want to cout << card (card being of class Card) and it output 7C (as in 7 of clubs) but I get an error at COUT << value that says

no operator << matches these operands

operand types are: std::ofstream << char

I'm not sure if I set up the overloading function correctly or if it is another issue. There is more in class Card but they don't relate to the problem I'm having.

nickeno3
  • 23
  • 3
  • 2
    In particular, [this answer](https://stackoverflow.com/a/4421719/7976805). Typical `operator <<` should have signature `std::ostream& operator <<(std::ostream& os, const ClassType& object)` and it cannot be a member of `ClassType`. If you need to access `private` members, make it a `friend` of your class. – Yksisarvinen Apr 25 '22 at 17:55
  • Also, small note: You probably just want the argument and return type to be `ostream&`, not `ofstream&`. There's no reason to restrict it to files. Are you _sure_ this is the function signature required in your assignment? – Nathan Pierson Apr 25 '22 at 18:07
  • this would be an example how you can implement it using a friend declaration: [godbolt example](https://godbolt.org/z/KMxKMEa6z) (also note that i'm casting `value` to int, to make sure it's outputted as a number instead of as a character) – Turtlefight Apr 25 '22 at 18:48

0 Answers0