home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,574 of 33,346   
   Francis Glassborow to Ethan   
   Re: member function as friend of a class   
   16 Oct 11 16:10:03   
   
   970ee117   
   From: francis.glassborow@btinternet.com   
      
   On 16/10/2011 14:29, Ethan wrote:   
   > Hello,   
   >   
   >   I'm trying to have a member function of a class to be a friend of   
   > another class, however, i get this error   
   > Am i missing anything?   
      
   Yes, in this case the compiler needs to be able to see the definition of   
   the class. In the case you show there is not reason to forward declare   
   B, just replace the declaration with the definition. I attach my version   
   of your code below. Please look at it and note the chnages I have made.   
      
   >   
   > main.cpp:10: error: invalid use of incomplete type ‘struct B’   
   > main.cpp:3: error: forward declaration of ‘struct B’   
   >   
   > #include   
   >   
   > class B;   
   >   
   > class A {   
   > int a;   
   > public : A() { a = 5; }   
   >          void sample(B);   
   >          friend void B::sample();   
   > };   
   >   
   > class B {   
   > public : void sample() {   
   >              //printf("%d\n",obj.a);   
   >          }   
   > };   
   >   
   >   
      
   My version of your code:   
      
   #include    // better to use C++ i/o when writing C++   
      
       class B {   
       public:   
          void sample();  // you can define this function later   
       };   
      
       class A {   
       public:   // need to know ordering   
         friend void B::sample();   
         A(): a(5){} // use ctor/init list   
        private:   
          int a;   
       };   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca