2

I don't know the term in programing of what I'm asking (this is hobby for me) and I'm trying to new things here. See my working escenario:

#include <iostream>

class Foo {
    int _x;
    public:
        Foo () : _x(0) {}
        Foo (int x) : _x(x) {}
        int get () const { return _x; }
};

int main () {
    Foo f1;
    Foo f2(10);
    std::cout << "Value: " << f1.get () << std::endl; // 0
    std::cout << "Value: " << f2.get () << std::endl; // 10
    return 0;
}

Is it possible to use either f1 or f2 like this:

std::cout << "Value: " << f2 << std::endl; // shows 10

updated with correct code:

#include <iostream>

class Foo {
    int _x;
    public:
        Foo () : _x(0) {}
        Foo (int x) : _x(x) {}
        int get () const { return _x; }
        friend std::ostream &operator<<(std::ostream &os, const Foo& f) { 
            return os << f.get ();
        }
};

int main () {
    Foo f1;
    Foo f2(10);
    std::cout << "Value: " << f1.get () << '\n'; // 0
    std::cout << "Value: " << f2.get () << '\n'; // 10
    std::cout << "Value: " << f1 << '\n'; // 0
    return 0;
}
Joel
  • 1,805
  • 1
  • 22
  • 22

1 Answers1

2

Yes, this is overloading stream insertion operator.

#include <iostream>

class Foo {
    int _x;
    public:
        Foo () : _x(0) {}
        Foo (int x) : _x(x) {}
        int get () const { return _x; }
        friend std::ostream& operator<< ( std::ostream& stream, const Foo& foo );
};

std::ostream& operator<< ( std::ostream& stream, const Foo& foo ) {
    stream << foo._x;
    return stream;
}

int main () {
    Foo f1;
    Foo f2(10);
    std::cout << "Value: " << f1 << std::endl; // 0
    std::cout << "Value: " << f2 << std::endl; // 10
    return 0;
}
oklas
  • 7,935
  • 2
  • 26
  • 42
  • 1
    A good answer should explain how to do something, not just link to elsewhere. Outside links could die, not be accessible, etc. And for the links that are on SO, then the question should be closed as a duplicate of one of those. – BoBTFish Mar 05 '16 at 19:22
  • thanks, answer is improoved – oklas Mar 05 '16 at 19:32