Virtual friend functions for a base class?

前端 未结 5 678
情书的邮戳
情书的邮戳 2020-12-14 21:56

I\'m in the proccess of learning the language and this is a noob doubt.

Is it possible to use a virtual friend function? I don\'t know if it\'s possible, I didn\'t

5条回答
  •  萌比男神i
    2020-12-14 22:19

    You can solve this without friend functions, using public virtual methods only:

    struct BaseClass {
      virtual void print(std::ostream& os) const;
    };
    
    struct DerivedClass {
      virtual void print(std::ostream& os) const;
    };
    
    std::ostream& operator<<(std::ostream& os, const BaseClass& obj) {
      obj.print(os);
      return os;
    }
    

    If it doesn't make sense for the print method to be public, then the ostream& operator<< can be declared as friend.

提交回复
热议问题