C ++:授予成员函数友情前瞻声明?

时间:2012-12-21 17:08:27

标签: c++ friend access-control forward-declaration

我在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提供了另一个类似的示例,但示例无法在我的计算机上运行,​​所以我是否需要检查一些编译器标志或什么?

1 个答案:

答案 0 :(得分:3)

交换它?

class A;

class B
{
public:
int fun(A inst);
private:
int b;
};

class A
{
friend int B::fun(A A);
private:
int a;
};

int B::fun(A A)
{   int N = A.a + b;
return N;
}