How can I use cout << myclass

C++ClassInputInteger

C++ Problem Overview


myclass is a C++ class written by me and when I write:

myclass x;
cout << x;

How do I output 10 or 20.2, like an integer or a float value?

C++ Solutions


Solution 1 - C++

Typically by overloading operator<< for your class:

struct myclass { 
    int i;
};

std::ostream &operator<<(std::ostream &os, myclass const &m) { 
    return os << m.i;
}

int main() { 
    myclass x(10);

    std::cout << x;
    return 0;
}

Solution 2 - C++

You need to overload the << operator,

std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
      os << obj.somevalue;
      return os;
}

Then when you do cout << x (where x is of type myclass in your case), it would output whatever you've told it to in the method. In the case of the example above it would be the x.somevalue member.

If the type of the member can't be added directly to an ostream, then you would need to overload the << operator for that type also, using the same method as above.

Solution 3 - C++

it's very easy, just implement :

std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
   os << foo.var;
   return os;
}

You need to return a reference to os in order to chain the outpout (cout << foo << 42 << endl)

Solution 4 - C++

Even though other answer provide correct code, it is also recommended to use a hidden friend function to implement the operator<<. Hidden friend functions has a more limited scope, therefore results in a faster compilation. Since there is less overloads cluttering the namespace scope, the compiler has less lookup to do.

struct myclass { 
    int i;

    friend auto operator<<(std::ostream& os, myclass const& m) -> std::ostream& { 
        return os << m.i;
    }
};

int main() { 
    auto const x = myclass{10};
    std::cout << x;

    return 0;
}

Solution 5 - C++

Alternative:

struct myclass { 
    int i;
    inline operator int() const 
    {
        return i; 
    }
};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaliView Question on Stackoverflow
Solution 1 - C++Jerry CoffinView Answer on Stackoverflow
Solution 2 - C++Rich AdamsView Answer on Stackoverflow
Solution 3 - C++Tristram GräbenerView Answer on Stackoverflow
Solution 4 - C++Guillaume RacicotView Answer on Stackoverflow
Solution 5 - C++Emil MocanView Answer on Stackoverflow