C++ 如何仅为一个特定的函数和类声明友元函数?

C++ 如何仅为一个特定的函数和类声明友元函数?,c++,friend-function,C++,Friend Function,我的代码怎么了 我试图在GNU G++环境中编译下面的代码,但出现以下错误: 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: ‘in

我的代码怎么了

我试图在GNU G++环境中编译下面的代码,但出现以下错误:

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
成员函数必须首先在其类中声明,而不是在友元声明中声明。这一定意味着在友元声明之前,您应该定义它的类——仅仅一个转发声明是不够的

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);
 }

成员函数必须首先在其类中声明,而不是在友元声明中声明。这一定意味着在友元声明之前,您应该定义它的类——仅仅一个转发声明是不够的

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);
 }