【问题标题】:Calling Protected Function From Derived Friend Function从派生的朋友函数调用受保护的函数
【发布时间】:2015-08-26 09:28:50
【问题描述】:

我有一个基类Animal 和一个派生类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;
}

【问题讨论】:

  • eat() 未声明为静态...
  • 您需要任何Animal 实例(例如Lion)来调用它:leo.eat(lhs, rhs, &amp;hungry);

标签: c++ oop friend derived-class


【解决方案1】:

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

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

【讨论】:

  • 啊,是的——没错。即使访问私有成员也必须从对象完成,例如lhs.mass
猜你喜欢
  • 2014-09-28
  • 2015-08-18
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2023-03-07
  • 2020-08-13
  • 1970-01-01
相关资源
最近更新 更多