【问题标题】:How should I properly use a friend declaration in a nested class?我应该如何在嵌套类中正确使用朋友声明?
【发布时间】:2018-10-27 06:04:06
【问题描述】:

例如,假设我编写了这样的代码:

class A
{
private:
    class B
    {
    private:
        int a;
        friend int A::foo(B &b);
    };
    int foo(B &b)
    {
        return b.a;
    }
};

由于B 中的a 是私有的,因此要在A 的函数foo 中使用a,我将使用friend,以便foo 可以实际访问a

但是,此代码给出了无法访问a 的错误。代码有什么问题,我应该如何更改代码同时保持a 私有且A 不是B 的朋友?还是有更好的办法?

【问题讨论】:

  • “和 A 不是 B 的朋友”你的意思是 B 不是 A 的朋友?我很确定这是不可能的,因为您需要事先完整定义 A 或 B。
  • aclass B 内部是私有的。要访问类的私有成员,您可能需要class B 中的公共方法,例如int get_a() { return a; }

标签: c++ class oop c++11 friend


【解决方案1】:

如果您只想获取B 类的a,则需要一个getter 函数。这应该是最简单的方法。

class B
{
private:
    int a;
public:
    // provide getter function
    const int& getMember_a()const { return a; }
};

foo函数中

const int& foo(const B &b)const 
{
    return b.getMember_a(); // call the getter to get the a
}

关于您的代码问题;在B 类中的friend int A::foo(B &b); 行,它不知道函数A::foo。因此我们需要在B 类之前转发声明int foo(B &);。然后是问题; A::foo(B &) 是否知道 B。也没有。但幸运的是,C++ 也允许通过前向声明类来获得不完整的类型。就是说,顺着路,你就可以达到你想要的目标。

class A
{
private:
    class B;      // forward declare class B for A::foo(B &)
    int foo(B &); // forward declare the member function of A
    class B
    {
    private:
        int a;
    public:
        friend int A::foo(B &b);
    };
};
// define, as a non-member friend function
int A::foo(B &b)
{
    return b.a;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多