I study C , I am also not strong in it, so do not judge strictly, played with classes, and decided to make 2 classes so that you can try their prototypes, to which I received in response, in the 1st case, not a complete description of the class, and in the second There is no access to the fields and in general to class. I watched the lesson on the OOP, and there the person worked this code, I decided to try myself what I was surprised, and I don't even know what to do who can explain why and how, I will be happy to hear. thanks in advance.
class human;
class apple {
private:
int weight;
string color;
public:
apple(const int weight, const string color) {
this->weight = weight;
this->color = color;
}
friend void human::take_apple(apple& app);
};
class human {
public:
void take_apple(apple& app) {};
};
Error: Incomplete type 'human' named in nested name specifer.
class apple;
class human {
public:
void take_apple(apple& app) {
cout << app.color << '\n';
};
};
class apple {
private:
int weight;
string color;
public:
apple(const int weight, const string color) {
this->weight = weight;
this->color = color;
}
friend void human::take_apple(apple& app);
};
Error: Member access into incomplete type 'apple'.
CodePudding user response:
Before befriending a member function, there must be a declaration for that member function in the respective class(which is human
in this case).
To solve this you can declare the member function before and the define it afterward the class apple
's definition as shown below:
class apple; //friend declaration for apple
class human {
public:
void take_apple(apple& app);//this is a declaration for the member function
};
class apple {
private:
int weight;
std::string color;
public:
apple(const int weight, const std::string color) {
this->weight = weight;
this->color = color;
}
friend void human::take_apple(apple& app);
};
//this is the definition of the member function
void human::take_apple(apple& app) {};
Note: In case you want to put the implementation of member function take_apple
inside a header file make sure that you use the keyword inline
.