Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use cout << myclass

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?

like image 920
ali Avatar asked Jun 05 '10 19:06

ali


People also ask

Can you cout objects?

The cout object in C++ is an object of class ostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout.

How do you add two objects in C++?

yes of course you can add two object of same class but before doing that you have to do operator overloading , by defining the '+' operator and how the objects are going to add when u simply put a '+' operator between the object.


1 Answers

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; } 
like image 188
Jerry Coffin Avatar answered Sep 27 '22 19:09

Jerry Coffin