Overloading « for cout

Overloading with free function

#include <iostream>

class Cat {
    int age;
public:
    Cat(int age) : age(age) {};
    int getAge() const { return age; }
};

std::ostream& operator<<(std::ostream& out, const Cat& rhsCat) {
    return out << "Cat is " << rhsCat.getAge() << " years old.";
}

int main() {
    Cat cat(3);
    std::cout << cat << std::endl;

    return 0;
}

Overloading with friend function

Now has access to cat’s private members:

#include <iostream>

class Cat {
    int age;
public:
    Cat(int age) : age(age) {};
    int getAge() const { return age; }
    friend std::ostream& operator<<(std::ostream& out, const Cat& rhsCat);
};

std::ostream& operator<<(std::ostream& out, const Cat& rhsCat) {
    return out << "Cat is " << rhsCat.age << " years old.";
}

int main() {
    Cat cat(3);
    std::cout << cat << std::endl;

    return 0;
}

Overloading +, ==, ()

#include <iostream>

class Vector {
    float x,y;
public:
    Vector (float x, float y) : x(x), y(y) {};
    /*
    Vector operator+(const Vector& other) const {
        return Vector(x + other.getX(), y + other.getY());
    }
     */
    float getX() const { return x; }
    float getY() const { return y; }
    bool operator==(const Vector& other) const { return (x == other.x) && (y == other.y); }
    void operator()() { std::cout << "Call me baby!" << std::endl; }

};

Vector operator+(const Vector& lhs, const Vector& rhs) {
    return Vector(lhs.getX() + rhs.getX(), rhs.getY() + rhs.getY());
}

int main() {
    Vector a(1, 2);
    Vector b(3, 4);
    std::cout << (a + b).getX() << std::endl;
    Vector c(3,4);
    if (b == c) {
        std::cout << "b equals c" << std::endl;
    }
    c();
    return 0;
}
4
b equals c
Call me baby!

Categories: