想象一下如下設置。如何從派生類cout
中調用基類cout
?我可以使用getBrand()
方法,但我覺得我應該能夠直接訪問基類'cout
朋友函數。如何從派生類中調用重載的父cout朋友類?
我砍了一下,試了this.Brand
,也只是Brand
。沒有運氣。
class Brand {
public:
Brand(std::string brand):brand_(brand) {};
friend std::ostream & operator << (std::ostream & out, const Brand & b) {
out << b.brand_ << ' ';
return out;
}
std::string getBrand()const { return brand_; }
private:
std::string brand_;
}
class Cheese : public Brand {
public:
Cheese(std::string brand, std::string type):Brand(brand), type_(type) {};
friend std::ostream & operator << (std::ostream & out, const Cheese & c) {
out << /* THIS.BRAND?! BRAND?! getBrand() meh.. */ << ' ' << c.type_ << std::endl; // <-- HERE
return out;
}
private:
std::string type_;
}
int main() {
Cheese c("Cabot Clothbound", "Cheddar");
std::cout << c << std::endl;
}
所需的輸出
Cabot Clothbound Cheddar
當Brand的'operator <<'將尾部換行放入流中時,輸出應該如何成爲'Cabot Clothbound Cheddar'? – Zereges
好點,但在旁邊。編輯並刪除。 – kmiklas