问题
What's wrong with my code?
I tried to compile the code below in the GNU G++ environment and I get these errors:
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;
}
回答1:
A member function must be first declared in its class (not in a friend declaration). That must mean that prior to the friend declaration, you should have the class of it defined - a mere forward declaration does not suffice.
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);
}
来源:https://stackoverflow.com/questions/1966255/how-can-friend-function-be-declared-for-only-one-particular-function-and-class