How can I use cout << myclass

ali picture ali · Jun 5, 2010 · Viewed 52.6k times · Source

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?

Answer

Jerry Coffin picture Jerry Coffin · Jun 5, 2010

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;
}