注册 登录
编程论坛 C++教室

友元函数的实现位置

meweiwei 发布于 2007-06-10 20:05, 627 次点击
按我个人的理解,友元函数不是类的成员函数,所以当把类B的一个函数F()声明为类A的友元时,函数的实现要在类A和类B之后实现.
请问我这种理解对吗?
为什么当把一个普通函数FUN()声明为类A的友元函数时,友元函数FUN()却可以在类A内实现?
2 回复
#2
meweiwei2007-06-12 11:56

怎么没有人回复我啊?

#3
HJin2007-06-12 12:10

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]

1