2009-12-27 6 views
1

Quel est le problème avec mon code?Comment une fonction amie peut-elle être déclarée pour une seule fonction et classe particulière?

J'ai essayé de compiler le code ci-dessous dans l'environnement GNU G ++ et je reçois ces erreurs:

 
friend2.cpp:30: error: invalid use of incomplete type ‘struct two’ 
friend2.cpp:5: error: forward declaration of ‘struct two’ 
friend2.cpp: In member function ‘int two::accessboth(one)’: 
friend2.cpp:24: error: ‘int one::data1’ is private 
friend2.cpp:55: error: within this context 
#include <iostream> 
using namespace std; 

class two; 

class one 
{ 
    private: 
     int data1; 
    public: 
     one() 
     { 
      data1 = 100; 
     } 

     friend int two::accessboth(one a); 
}; 

class two 
{ 
    private: 
     int data2; 

    public: 
     two() 
     { 
      data2 = 200; 
     } 

     int accessboth(one a); 
}; 

int two::accessboth(one a) 
{ 
    return (a.data1 + (*this).data2); 
} 

int main() 
{ 
    one a; 
    two b; 
    cout << b.accessboth(a); 
    return 0; 
} 

Répondre

9

Une fonction membre doit être d'abord déclaré dans sa catégorie (pas dans une déclaration d'ami). Cela doit signifier qu'avant la déclaration de l'ami, vous devriez en définir la classe - une simple déclaration avant ne suffit pas.

class one; 

class two 
{ 
    private: 
    int data2; 
    public: 
    two() 
    { 
    data2 = 200; 
    } 
// this goes fine, because the function is not yet defined. 
int accessboth(one a); 
}; 

class one 
{ 
    private: 
    int data1; 
    public: 
    one() 
    { 
    data1 = 100; 
    } 
    friend int two::accessboth(one a); 
}; 

// don't forget "inline" if the definition is in a header. 
inline int two::accessboth(one a) { 
    return (a.data1 + (*this).data2); 
} 
Questions connexes