64,682
社区成员
发帖
与我相关
我的任务
分享
//A.h
class A
{
private:
int val_a;
friend void B::GetValueA(B *pB);
...
}
//A.cpp
#include"A.h"
...
//B.h
class B
{
private:
int val_b;
void GetValueA(A *pA);
}
//B.cpp
#include"B.h"
void B::GetValueA(A *pA)
{
val_b = pA->val_A;
}
//main.cpp
#include"A.h"
#include"B.h"
......
。
//main.cpp
class A;
class B
{
private:
int b;
public void func(A * pA);
};
class A
{
private:
int a;
friend void B::func(A * pA);
};
void B::func(A * pA)
{
b= pA->a;
}
int main()
{
cout<<"Compile Success!"<<endl;
return 0;
}
2. 若类A和类B分别定义在不同的文件中,则建议在类A中声明类B为类A的友元类,然后调用类B中的公有函数访问类A的私有成员。具体实例如下:
//A.h
#ifndef A_H_
#define A_H_
#include"B.h"
class B;
class A
{
private:
int a;
friend class B;
};
#endif /* A_H_ */
//A.cpp
......
//B.h
#ifndef B_H_
#define B_H_
#include"A.h"
class A;
class B
{
private:
int b;
void func(A * pA);
};
#endif
//B.cpp
#include"B.h"
......
void B::func(A * pA)
{
b=pA->a;
}
//main.cpp
int main()
{
return 0;
}
此时,编译通过,并可通过类B的对象访问类A对象的私有成员。
A.h
#ifndef _A_H
#define _A_H
class B;
class A
{
private:
int val_a;
friend class B;
};
#endif
[code=c]
B.h
#include "A.H"
#ifndef _B_H_
#define _B_H_
class B
{
private:
int val_b;
void GetValueA(A *pA);
};
void B::GetValueA(A *pA)
{
val_b = pA->val_a;
}
#endif
[/code]class A
{
private:
int val_a;
friend void B::GetValueA(B *pB);
...
}
这中设计真不好,你要么放到类A外面,要么跟B.cpp放一起!就你现在的问题而言,在A.h中,添加class B就行了