2012-12-21 69 views
-1

我在C++中遇到了問題。我有兩個類,A和B,其中B的定義使用了A的一些實例。我也想給B中的成員函數訪問A中的私有數據成員,因此賦予它友誼。但是現在,難題是對於A類定義中的友誼聲明,B類尚未定義,所以IDE(VS 2010)不知道該怎麼做。C++:授予成員函數友誼向前聲明?

#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提供了另一個類似的例子,但這個例子無法在我的電腦上運行,所以我需要檢查一些編譯器標誌或什麼?

回答

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; 
} 
+0

這還不夠,有循環依賴 – SomeWittyUsername

+0

確定在這裏工作... :) – JasonD

+0

我想也和它的作品 –