Udostępnij za pośrednictwem


Friend Declarations

If you declare a friend function that was not previously declared, that function is exported to the enclosing nonclass scope.

Functions declared in a friend declaration are treated as if they had been declared using the extern keyword. (For more information about extern, see Static Storage-Class Specifiers.)

Although functions with global scope can be declared as friends prior to their prototypes, member functions cannot be declared as friends before the appearance of their complete class declaration. The following code shows why this fails:

class ForwardDeclared;   // Class name is known.
class HasFriends
{
    friend int ForwardDeclared::IsAFriend();   // C2039 error expected
};

The preceding example enters the class name ForwardDeclared into scope, but the complete declaration — specifically, the portion that declares the function IsAFriend — is not known. Therefore, the friend declaration in class HasFriends generates an error.

To declare two classes that are friends of one another, the entire second class must be specified as a friend of the first class. The reason for this restriction is that the compiler has enough information to declare individual friend functions only at the point where the second class is declared.

Note

Although the entire second class must be a friend to the first class, you can select which functions in the first class will be friends of the second class.

See Also

Reference

friend (C++)