Volodymyr Samoilenko
Volodymyr Samoilenko

Reputation: 358

Cannot make overload operator<< with included private class

Can some one explain me, how to make overload with private class variables? I tried to use pointer in overload, but maybe i should use ostream& operator<<(ostream& out, B& b) or ostream& operator<<(ostream& out, const B& b)?

#include <iostream>
using namespace std;

class B {
    const int x = 5;
public:
    B(){}
    ~B(){}
    int get_x() {
        return this->x;
    }
};
ostream& operator<<(ostream& out, B *b) {
    return out << b->get_x();
}

class A {
    B b;
public:
    A(){}
    ~A() {}
    B get_b() {
        return this->b;
    }
};
ostream& operator<<(ostream& out, A *a) {
    return out;
}

int main(int argc, const char * argv[]) {
    A *a = new A();
    cout << a << '\n';
    return 0;
}

Upvotes: 1

Views: 56

Answers (1)

user2100815
user2100815

Reputation:

You should not be using pointers, and you need to pay attention to constness:

#include <iostream>
using namespace std;

class B {
    const int x = 5;
public:
    B(){}
    ~B(){}
    int get_x() const {
        return this->x;
    }
};
ostream& operator<<(ostream& out, const B & b) {
    return out << b.get_x();
}

class A {
    B b;
public:
    A(){}
    ~A() {}
    B get_b() const {
        return this->b;
    }
};
ostream& operator<<(ostream& out, const A & a) {
    return out << a.get_b();
}

int main() {
    A a;
    cout << a << '\n';
    return 0;
}

Upvotes: 3

Related Questions