从派生友元函数调用受保护函数

Calling Protected Function From Derived Friend Function

我有一个基数 class、Animal 和一个派生的 class、LionAnimal 有一个名为 eat() 的受保护函数。我想从 Lion 中定义的友元函数调用 eat(),但当它无法编译时:

error: call to non-static member function without an object argument

为什么我不能调用 Lion 朋友的受保护函数?我有变通办法,但我不明白为什么朋友不能打电话给 eat()。使用 Animal::eatLion::eat 似乎并不重要,我得到相同的错误。想法?

#include <iostream>
using namespace std;

class Animal{
public:
    Animal(int m) : mass(m){}
    int getMass() const { return mass; }
protected:
    int mass;
    void eat(const Animal& lhs, const Animal& rhs, Animal *result){
        result->mass = lhs.getMass() + rhs.getMass();
    }
};

class Gazelle : public Animal{
public:
    Gazelle(int m) : Animal(m){}
};

class Lion : public Animal{
public:
    Lion(int m) : Animal(m){}

    friend Lion feed(const Lion &lhs, const Gazelle &rhs){
        Lion hungry(0);
        eat(lhs, rhs, &hungry);
        return hungry;
    }
};

int main(void){
    Lion leo(5);
    Gazelle greg(1);

    Lion fullLeo = feed(leo, greg);
    cout << "Full Leo has mass " << fullLeo.getMass() << endl;
}

friend 函数是一个非成员函数,它可以访问 class 的私有成员。但是您仍然必须提供访问数据成员的对象详细信息。

eat函数的用法必须与feed函数中的object_name.eat()类似。