【发布时间】:2012-09-21 00:03:07
【问题描述】:
所以我有 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 和 B 有自己的头文件和正文文件。
【问题讨论】:
-
您是否考虑过让运算符重载成为 A 的成员?
-
@Borgleader:你不能让 operator
-
@SethCarnegie:由于答案已经确定,我删除了我的评论(我知道这是错误的;)
-
@bstamour:哦,你是对的 -.-;
标签: c++ inheritance operators