friend problem

Hi, I think I have misunderstood friend keyword. I'm trying following:

class X
{
friend class Y;
friend void f(){}
};

class Z
{
Y *p;
void g(){ return ::f();}
};

int main()
{ return 0; }

error: ISO C++ forbids declaration of ‘Y’ with no type
‘::f’ has not been declared

Friend keyword puts class Y to outer scope so class Y should be global declared class and available in class Z. Another problem is with friend function which is defined in class Y, so function call f() in Z class should succeed. Reference: 466 page C++ primer 4th edition (Friend declaration and scope).

Anyone has a explanation why program wont compile?
Sorry if my English is not good as it should be...
Well, nowhere have you shown a declaration for class Y. You've shown declarations for X and Z.
To my understanding, only friend member functions require class definition to be present before friend declaration. Friend class-es and non-member functions need not to be declared to be made a friend. It is written that the scope of friend declaration inside function is exported to enclosing scope. So class Y and function f() are in the global scope in this case, so it should be possible to use them in class Z (pointer and references of declared non-defined classes persist). Alias:

class Y;
void f(){}

class X
{
.
.
.
Words of wisdom appreciated...
The first problem is that in order to declare a variable of type Y* (p member in Z), you must at least forward declare Y.

Second, saying

 
friend void f(){}


declares void f() to be a friend of X, but it does not actually declare void f(). This compiles for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class X
{
friend class Y;
friend void f();     // Removed implemention from here;  not a declaration of f().
};

void f(){}        // Added declaration of f() and implementation of f()

class Y;
class Z
{
Y *p;
void g(){ return ::f();}
};

int main()
{ return 0; }
Yes I understand that but I don't understand friend keyword.....I quote : "The scope of the function is exported to the scope enclosing the class definition". The example I have given is copied from the book with comment that Y class in Z class is introduced by friend in x. No forward declaration is given. Further more the definition of the function f as friend in class X isn't declared globally. So I think the best solution would be to explain in detail friend keyword. I would appreciated that....
You understand the keyword friend better than the book. The book you have is wrong. friend void f(); simply says that void f() is a friend of X -- nothing more. It is simply a statement of friendship. It does not serve as a declaration of the function f(). In my code above, line 13 references f(). It is line 7, not line 4, that declares f().

Thank you for your trouble, reps where helpful....I will try to find another explanation before I question the book. But it seems that keyword isn't that kind of mystery after all. TNX...
Topic archived. No new replies allowed.