So I have class A and class B, where class B extends class A. I must overload the << and >> in both classes. I was hoping that in the function definition of the operators for class B, I could call the overloaded operators from class A, but I’m having trouble doing so.
#include <iostream>
#include <string>
using namespace std;
class A {
friend ostream& operator<<(ostream& out, A a);
protected:
int i;
string st;
public:
A(){
i=50;
st = "boop1";
}
};
ostream& operator<<(ostream &out, A a) {
out << a.i << a.st;
return out;
}
class B : public A {
friend ostream& operator<<(ostream& out, B b);
private:
int r;
public:
B() : A() {
r=12;
}
};
ostream& operator<<(ostream &out, B b) {
out = A::operator<<(out, b); //operator<< is not a member of A
out << "boop2" << b.r;
return out;
}
int main () {
B b;
cout << b;
}
I attempt to call A’s version of operator<< in B’s version of operator<<, but of course it doesn’t actually belong to A, so it cannot compile. How should I be achieving this?
also, note that in reality A and B have their own header and body files.
You can make your
Bobject look like anAobject:Note that you almost certainly don’t want to pass the object to be printed by value. I have changed the signature to use a
const&instead: This indicates that the object won’t get changed and it won’t get copied.