【发布时间】:2015-08-26 09:28:50
【问题描述】:
我有一个基类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;
}
【问题讨论】:
-
eat()未声明为静态... -
您需要任何
Animal实例(例如Lion)来调用它:leo.eat(lhs, rhs, &hungry);
标签: c++ oop friend derived-class