我正在学习课堂和朋友功能。 我希望Farm类中的函数eat()从Bull类中访问可变价格并更改价格值。所以我需要实现一个朋友功能。我在使用函数时遇到问题,因为我不知道如何使用它。 我遇到了那些错误:
gcc friendFClass.cc -lstdc++ -o friendFClass
friendFClass.cc: In member function 'void Farm::eat(Bull)':
friendFClass.cc:43: error: 'class Bull' has no member named 'eat'
friendFClass.cc: In function 'int main()':
friendFClass.cc:54: error: 'class Bull' has no member named 'eat'
此程序:
#include <iostream>
class Bull; // declaration not full of Bull
class Farm { // declaration full of Farm
double sizeFarm;
double massBull;
public:
void eat(Bull eatingBull); // Ok Bull was declared
void init(double size, double mass) {
this -> sizeFarm = size;
this -> massBull = mass;
}
void print() {
std::cout << "size of the Farm: " << sizeFarm << "\nmass of a bull: " << massBull << std::endl;
}
};
class Bull {
int eatBullThisMonth;
int price;
friend void Farm::eat(Bull eatingBull); // Ok Farm was full deblared
public:
void init(int price) {
this -> price = price;
}
void print() {
std::cout << "Number of bull for the month: " << eatBullThisMonth << std::endl;
std::cout << "Total price : " << price << std::endl;
}
};
void Farm::eat(Bull eatingBull) {
int pPrice = 12 * eatingBull.price;
eatingBull.eat(pPrice);
eatingBull.print();
}
int main() {
Farm delacroix;
Bull marguerite;
delacroix.init(1260, 123);
marguerite.init(159);
marguerite.eat();
return 0;
}
我不知道在类服务器场的内部或外部定义朋友函数的位置以及如何定义它。
谢谢。
答案 0 :(得分:0)
在另一个类中将函数声明为friend
意味着它可以访问其私有成员,而不是继承该方法。在这种情况下,这意味着Farm::eat
可以访问Bull
个私有成员,但是Bull
不继承Farm::eat
。
答案 1 :(得分:0)
现在可以解决问题了,因为这是对函数的滥用和对函数调用的滥用。这是正确的代码。
#include <iostream>
class Bull; // declaration not full of Bull
class Farm { // declaration full of Farm
double sizeFarm;
double massBull;
public:
void eat(Bull eatingBull); // Ok Bull was declared
void init(double size, double mass) {
this -> sizeFarm = size;
this -> massBull = mass;
}
void print() {
std::cout << "size of the Farm: " << sizeFarm << "\nmass of a bull: " << massBull << std::endl;
}
};
class Bull {
int eatBullThisMonth;
int price;
friend void Farm::eat(Bull eatingBull); // Ok Farm was full deblared
public:
void init(int price) {
this -> price = price;
}
void print() {
std::cout << "Number of bull for the month: " << eatBullThisMonth << std::endl;
std::cout << "Total price : " << price << std::endl;
}
};
void Farm::eat(Bull eatingBull) {
int pPrice = 12 * eatingBull.price;
eatingBull.init(pPrice);
eatingBull.print();
}
int main() {
Farm delacroix;
Bull marguerite;
delacroix.init(1260, 123);
marguerite.init(159);
delacroix.eat(marguerite);
return 0;
}