2014-06-30 141 views
1

我有以下幾點:朋友的成員函數不能訪問私有成員

class B; 

class A 
{ 
public: 
    int AFunc(const B& b); 
}; 

class B 
{ 
private: 
    int i_; 
    friend int A::AFunc(const B&); 
}; 

int A::AFunc(const B& b) { return b.i_; } 

對於AFunc定義我得到的成員B::i_無法訪問。我究竟做錯了什麼?

編譯器:MSVC 2013年

更新:改變AFunc公衆和代碼編譯現在。不過,我仍然收到一個智能感知錯誤。這是智能感知問題嗎?

回答

2

問題是,你是宣佈另一個類的private函數作爲friendB通常不知道A的私人會員功能。 G ++ 4.9有以下說:

test.cpp:6:9: error: 'int A::AFunc(const B&)' is private 
    int AFunc(const B& b); 
     ^
test.cpp:13:33: error: within this context 
    friend int A::AFunc(const B&); 
           ^

爲了解決這個問題,簡單地聲明BA朋友:

class A 
{ 
    friend class B; 
private: 
    int AFunc(const B& b); 
}; 

您可能會感興趣Microsoft's example

+4

來自C++ 11標準的確切引用(如果您想添加它)在11.3/9中:*由朋友聲明提名的名稱應在包含朋友聲明的類的範圍內可訪問。 –

+0

謝謝!我把'AFunc'改成了public(我真的在公開我的真實代碼)。現在編譯代碼,但我仍然收到一個IntelliSense錯誤。也許這是IntellSense的問題?更新的問題。 –

+0

代碼編譯,即使在' - pedantic'模式。我會說智能感知正在噴涌NonSense。 – thirtythreeforty