![](/img/trans.png)
[英]Use protected static function of the base class from the friend of the derived class
[英]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.