所以我有A類和B類,其中B類擴展了A類。我必須在兩個類中超載<和<。我希望在B類運算符的函數定義中,我可以調用A類的重載運算符,但是我很難這樣做。繼承C++中的朋友操作符
#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版的操作< <的,當然它實際上並不屬於A,所以不能編譯。我應該如何實現這一目標?
另外,請注意,實際上A和B都有自己的頭文件和正文文件。
你有沒有考慮讓操作符重載A的成員? – Borgleader
@Borgleader:你不能讓operator <<成爲A的成員,因爲A出現在操作符的右側,而不是左側。它必須是獨立功能或朋友功能。 – bstamour
@SethCarnegie:由於答案得到解決,我刪除了我的評論(我知道這是錯的;) –