我有以下内容:
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
更改为 public,代码现在可以编译。但是我仍然收到 IntelliSense 错误。这是 IntelliSense 的问题吗?
最佳答案
问题是您是将另一个类的private
函数声明为 friend
! B
通常应该不知道A
的私有(private)成员函数。 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&);
^
要解决这个问题,只需将 B
声明为 A
的好友即可:
class A
{
friend class B;
private:
int AFunc(const B& b);
};
您可能对 Microsoft's example 感兴趣.
关于c++ - 好友成员函数无法访问私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24494664/