无法使重载运算符<<包含私人课程

时间:2017-02-15 14:14:11

标签: c++

有人可以解释一下,如何使用私有类变量进行重载? 我尝试在重载时使用指针,但也许我应该使用ostream&运算符<(ostream& out,B& b)或ostream&运算符<<(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;
}

1 个答案:

答案 0 :(得分:3)

你不应该使用指针,你需要注意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;
}