【问题标题】:Friend member function cannot access private member好友成员功能无法访问私有成员
【发布时间】:2014-08-21 02:13:14
【问题描述】:

我有以下几点:

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 的问题吗?

【问题讨论】:

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


    【解决方案1】:

    问题是您正在将另一个类的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&);
                                     ^
    

    要解决这个问题,只需将B 声明为A 的朋友即可:

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

    您可能对Microsoft's example 感兴趣。

    【讨论】:

    • C++11 标准的准确引用(如果你想添加它)在 11.3/9 中: 由朋友声明指定的名称应在包含朋友声明的类。
    • 谢谢!我将AFunc 更改为公开(我实际上在我的真实代码中公开了它)。现在代码编译了,但我仍然收到 IntelliSense 错误。也许这是 IntellSense 的问题?更新的问题。
    • 代码编译,即使在-pedantic 模式下。我会说 IntelliSense 正在喷出 NonSense。
    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多