Virtual friend functions for a base class?

前端 未结 5 689
情书的邮戳
情书的邮戳 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:07

    Nope, friend virtual functions doesn't make sense at all.

    friend functions are such, that are not methods (a.k.a. member functions) and have the right to access private/protected members of a class.

    virtual functions can only be member functions. You can't have virtual non-member function.


    You can make the operator<< take a reference to a base class and then call some virtual member function. This way, you can make the operator<< "almost virtual" :)


    For example

    class A
    {
    public:
        virtual void f() const { std::cout << "base"; }
    };
    class B: public A
    {
    public:
        virtual void f() const { std::cout << "derived"; }
    };
    
    std::ostream& operator<<(std::ostream& os, const A& a )
    {
         a.f();
         return os;
    }
    
    int main()
    {
        B b;
        std::cout << b << std::endl;
    
        return 0;
    }
    

    will print derived.

提交回复
热议问题