Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c++ - Virtual friend functions for a base class?

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 even test it but it could be useful in some situations. For example, for the overloaded operator<<().

DerivedClass dc;
BaseClass &rbc = dc;
cout << rbc;

My guess is it's possible, but I'm not sure since a friend function is not implemented in the class design, and theoretically is not part of it (though in this example, conceptually it makes sense that operator<<() should be a method, but due to syntax limitations it's not possible to implement it as one).

EDIT: my concern is related with this example:

BaseClass bc;
DerivedClass dc;
BaseClass *pArr[2];
pArr[1] = bc;
pArr[2] = dc;
for (int i = 0; i < 2; i++)
    cout << pArr[i];

in this array of mixed objects, I want the correct operator<<() called for each one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...