c++ - 好友成员函数无法访问私有(private)成员

标签 c++ visual-c++ intellisense friend access-control

我有以下内容:

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/

相关文章:

c++ - Visual Studio 2010 在成功构建时崩溃

c++ - 包含两个 .cpp 文件和一个头文件的基本 Makefile

vb.net - 如何在 VB.NET for Visual Studio 2015 中显示片段?

c++ - 正如在 c 中解释的那样

visual-studio - 在 Visual Studio 2017 15.7 中禁用 Screwdriver

c# - 在 ICSharpCode.TextEditor 中配置智能感知

c++ - 无法创建窗口

c++ - 在 C++ 中确定对象是否动态分配

c++ - 派生类销毁期间纯虚函数的范围 - 在 C++ 中

c++ - CRT 未检测到 DLL 中的内存泄漏