【发布时间】:2017-11-22 06:28:00
【问题描述】:
设想如下设置。如何从派生类cout 中调用基类cout?我可以使用getBrand()方法,但我觉得我应该可以直接访问基类的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? -
好点,但题外话。已编辑和删除。
标签: c++ class oop c++11 inheritance