简体   繁体   中英

What's the difference between “friend struct A;” and “friend A;” syntax?

What is the difference between doing:

struct A;
struct B { friend struct A; };

and

struct A;
struct B { friend A; };

What does it mean to leave out struct in the second part?

The difference is that if you write friend A; , A must be a known type name, that is it must be declared before.

If you write friend struct A; , this itself is a declaration of A , so no prior declaration is needed:

struct B { friend struct A; }; // OK

There are several subtleties though. For example, friend class/struct A declares class A in innermost enclosing namespace of class B (thanks to Captain Obvlious ):

class A;
namespace N {
    class B {
        friend A;         // ::A is a friend
        friend class A;   // Declares class N::A despite prior declaration of ::A,
                          // so ::A is not a friend if previous line is commented
    };
}

Also there are several other cases when you can write only friend A :

  1. A is a typedef-name:

     class A; typedef A A_Alias; struct B { // friend class A_Alias; - ill-formed friend A_Alias; }; 
  2. A is a template parameter:

     template<typename A> struct B { // friend class A; - ill-formed friend A; }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM