繁体   English   中英

从派生朋友函数调用受保护的函数

[英]Calling Protected Function From Derived Friend Function

我有一个基类Animal ,还有一个派生类Lion Animal有一个受保护的函数,称为eat() 我想从Lion定义的一个朋友函数中调用eat() ,但是当它无法编译时:

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

为什么我不能从Lion的朋友那里调用受保护的函数? 我有解决方法,但是我无法弄清楚为什么朋友无法调用eat() 我使用Animal::eat还是Lion::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函数是非成员函数,可以访问类的私有成员。 但是您仍然必须提供对象详细信息以访问数据成员。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM