gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:38 27 4
gpt4 key购买 nike

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

期望的输出

Cabot Clothbound Cheddar

最佳答案

您可以调用重载的 operator <<来自派生类的基类。由于您将运算符声明为友元,因此您可以简单地将派生类转换为基类:

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_;
};

输出:

Cabot Clothbound Cheddar

See it Live

关于c++ - 如何从派生类调用重载的父 cout 友元类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640720/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com