[英]Calling Protected Function From Derived Friend Function
I have a base class, Animal
, and a derived class, Lion
. 我有一个基类
Animal
,还有一个派生类Lion
。 Animal
has a protected function called eat()
. Animal
有一个受保护的函数,称为eat()
。 I would like to call eat()
from a friend function defined in Lion
, but when it won't compile: 我想从
Lion
定义的一个朋友函数中调用eat()
,但是当它无法编译时:
error: call to non-static member function without an object argument
Why can't I call a protected function from a friend of Lion
? 为什么我不能从
Lion
的朋友那里调用受保护的函数? I have work-arounds, but I can't figure out why a friend wouldn't be able to call eat()
. 我有解决方法,但是我无法弄清楚为什么朋友无法调用
eat()
。 It doesn't seem to matter if I use Animal::eat
or Lion::eat
, I get the same error. 我使用
Animal::eat
还是Lion::eat
似乎都没有关系,但我得到了相同的错误。 Thoughts? 有什么想法吗?
#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;
}
A friend
function is a non member function which has access to private members of a class. friend
函数是非成员函数,可以访问类的私有成员。 But you still have to provide the object details for accessing data members. 但是您仍然必须提供对象详细信息以访问数据成员。
The usage of eat
function must be similar to object_name.eat()
in the feed
function. eat
函数的用法必须类似于feed
函数中的object_name.eat()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.