【发布时间】:2012-12-09 06:45:57
【问题描述】:
我对 C++ 中的友谊有疑问。我有两个类,A 和 B,其中 B 的定义使用了 A 的某个实例。我还想让 B 中的成员函数访问 A 中的私有数据成员,从而授予它友谊。但现在的难题是,对于 A 类定义中的友谊声明,B 类尚未定义,因此 IDE(VS 2010)不知道该怎么做。
#include <iostream>
using namespace std;
class B;
class A {
friend int B::fun(A A);//B as yet undefined here
int a;
};
class B {
int b;
public:
int fun(A inst);
};
int B::fun(A A)
{
int N = A.a + b;//this throws up an error, since a is not accessible
return N;
}
我查看了Why this friend function can't access a private member of the class?,但那里关于使用class B; 的前向声明的建议似乎不起作用。我怎样才能直接解决这个问题(即不诉诸于让class B成为class A的朋友,或者让B继承自A或引入getA()函数)?我还查看了Granting friendship to a function from a class defined in a different header,但我的课程在一个 .cpp 文件中(最好保持这种方式),而不是在单独的头文件中,而且我不想授予整个班级的友谊。同时,C++ Forward declaration , friend function problem 提供了一个稍微简单的问题的答案——我不能只更改定义的顺序。同时http://msdn.microsoft.com/en-us/library/ahhw8bzz.aspx提供了另一个类似的示例,但是示例无法在我的计算机上运行,所以我需要检查一些编译器标志什么的吗?
【问题讨论】:
标签: c++ friend access-control forward-declaration