想象一下如下设置。如何从派生类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