我们如何将Ostream函数作为类的成员函数实现,而不是作为朋友函数,以便我可以用作虚拟函数

How can we implement ostream function as member function of class ,and not as friend function so that i can be used as virtual function?

本文关键字:函数 我可以 朋友 虚拟 成员 Ostream 我们 实现      更新时间:2023-10-16

我想使用friend ostream&基类的功能,我们如何做到?如何使成员功能而不是类的成员函数,以便它可以用作虚拟函数并显示派生类的详细信息。

流插入器将流作为其第一个参数,因此当插入器是成员函数时,它是流类的成员,而不是您正在编写的类。因此,它不能是您班上的虚拟功能。但是它可以呼叫您的课程中的虚拟功能。

class my_class {
    virtual std::ostream& put(std::ostream& out) const {
        out << "here we go!b";
    }
friend std::ostream& operator<<(std::ostream& out, const my_class& my_object);
};
std::ostream& operator<<(std::ostream& out, const my_class& my_object) {
    my_object.put(out);
}