友元函数的实现位置
按我个人的理解,友元函数不是类的成员函数,所以当把类B的一个函数F()声明为类A的友元时,函数的实现要在类A和类B之后实现.请问我这种理解对吗?
为什么当把一个普通函数FUN()声明为类A的友元函数时,友元函数FUN()却可以在类A内实现?
try the following source code. I added only minimal comments. Good luck!
[CODE]#include <iostream>
using namespace std;
// This is a delcaration, but not a definition.
class A; // forward declaration (1)
class B
{
public:
void F();
void F2(A& a); // (1) is necessary since we need to know type A here
};
void B::F() // this needs type B to be defined
{
cout<<"B::F() called.\n";
}
class A
{
friend void B::F();
friend void B::F2(A& a);
private:
int i;
};
void B::F2(A& a) // this nees type both type B and A to be defined
{
a.i = 100;
cout<<"B::F2() called.\n";
}
int main(int argc, char** argv)
{
A objA;
B objB;
objB.F();
objB.F2(objA);
return 0;
}[/CODE]