如何从派生类调用重载的父cout友元类?

kmi*_*las 6 c++ oop inheritance class c++11

想象一下如下设置.如何cout从派生类中调用基类cout?我可以使用该getBrand()方法,但我觉得我应该能够直接访问基类的cout友元函数.

我砍了一下,然后尝试this.BrandBrand.没运气.

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;
} 
Run Code Online (Sandbox Code Playgroud)

期望的输出

Cabot Clothbound Cheddar
Run Code Online (Sandbox Code Playgroud)

Whi*_*TiM 6

您可以operator <<从派生类调用Base类的重载.因为,您将运算符声明为朋友,您可以简单地将派生类强制转换为基类:

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) {

        //ADDED
        out << static_cast<const Brand&>(c) << c.type_ << std::endl;
        return out;
    }
private:
    std::string type_;
};
Run Code Online (Sandbox Code Playgroud)

输出:

Cabot Clothbound Cheddar
Run Code Online (Sandbox Code Playgroud)

看到它直播