所以我有 A 类和 B 类,其中 B 类扩展了 A 类。我必须在两个类中重载 << 和 >>。我希望在 B 类的运算符的函数定义中,我可以从 A 类调用重载的运算符,但我在这样做时遇到了麻烦。
#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;
}
我尝试在 B 的 operator<< 中调用 A 的 operator<<,但当然它实际上并不属于 A,因此无法编译。我应该如何实现这一目标?
另外,请注意,实际上 A 和 B 有自己的头文件和正文文件。