Why wont this compile?

I tried putting the out of class function in the class and declaring it a friend but i couldnt do it. How do i change it to make it compile?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>

class Animal;

void setValue(Animal&, int);

class Animal
{
public:
    int GetWeight()const { return itsWeight;}
    int GetAge()const { return itsAge;}
private:
    int itsWeight;
    int itsAge;
};

void setValue(Animal& theAnimal, int theWeight)
{
    friend class Animal;
    theAnimal.itsWeight = theWeight;
}

int main()
{
Animal peppy
setValue(peppy,5);
}
If something does not compile, then compiler tells the points that confuse it:
 In function 'void setValue(Animal&, int)':
19:5: error: 'friend' used outside of class
13:9: error: 'int Animal::itsWeight' is private
20:15: error: within this context
 In function 'int main()':
26:1: error: expected initializer before 'setValue' 

What did those say?

1. Nothing can be a friend of a function. Functions and classes can be a friend of a class. The setValue() could/should be a member of Animal.

2. Without friendship the line 20 is access violation.

3. What is the last character of line 25? That shows as error on line 26.


You have to learn to decipher the compiler's messages.
Topic archived. No new replies allowed.