Canavirtualfunctionbeafriendofanotherclass?

Everywhere in theory, it is written that "A virtual function can be declared as a friend of another class", but practically on implementing it, the compiler throws an error saying "virtual functions cannot be friends".

Here is a C++ program to illustrate this:

#include <iostream>
using namespace std;

class extra;
class base {
public:
    virtual friend  void print(extra e);

    void show()
    {
        cout << "show base class" << endl;
    }
};

class derived : public base {
public:
    void print()
    {
        cout << "print derived class" << endl;
    }

    void show()
    {
        cout << "show derived class" << endl;
    }
};

class extra
{
    int k;
public:
    extra()
    {
        k=1;
    }
    friend void print(extra e);
};

void print(extra e)
{
    cout<<"virtual friend function "<<e.k;
}

int main()
{    
    base* bptr;
    extra e;
    derived d;
    bptr = &d;

    // virtual function, binded at runtime
    bptr->print(e);

    // Non-virtual function, binded at compile time
    bptr->show();
    print(e);
}

输出画面:

回答

当你写

virtual friend void print(extra e);

C++ 将此解释为“有一个名为 的自由函数print,它不是当前类的成员函数,它是虚拟的”。这种组合不可能发生,因为虚函数必须是类的成员函数。

您可以做的是获取在另一个类中定义的现有虚函数,并使其成为该类的朋友。所以,例如,如果有一个虚函数OtherClass::myFn,你可以写

friend void OtherClass::myFn();

说“那个特定的虚函数是我的朋友。” 不过,请注意,这只是让OtherClass::myFn班级成为朋友;任何覆盖OtherClass::myFn都不会成为班级的朋友,因为友谊不会被继承。


以上是Canavirtualfunctionbeafriendofanotherclass?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>