简体   繁体   English

我应该如何在嵌套类中正确使用友元声明?

[英]How should I properly use a friend declaration in a nested class?

For example, suppose I made a code like : 例如,假设我创建了一个代码:

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

Since a in B is private, to use a in function foo of A , I would use a friend so that foo can actually access a . 由于aB是私有的,用a函数fooA ,我会用一个friendfoo实际上可以访问a

However this code gives error that it cannot access a . 但是,此代码会出现无法访问a错误。 What is the problem of the code, and how should I change the code while keeping a private and A not being friend of B ? 什么是代码的问题,我应该怎么更改代码,同时保持a私人和A不被朋友B Or is there a better way? 或者,还有更好的方法?

If you want to get only the a of B class you need a getter function. 如果你只想获得B类的a ,你需要一个getter函数。 This should be the simplest way to go. 这应该是最简单的方法。

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

and in the foo function 并在foo函数中

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

Regarding the issue of your code; 关于你的代码问题; at the line friend int A::foo(B &b); 在线friend int A::foo(B &b); in B class, it does not know that the function A::foo . B类中,它不知道函数A::foo Therefore we need to forward declare int foo(B &); 因此我们需要转发声明int foo(B &); before the class B . B班之前。 Then the question; 然后问题; whether A::foo(B &) knows about B . 是否A::foo(B &)知道B Also no. 也没有。 But fortunately, C++ allows having an incomplete type by forward declaring the classes as well. 但幸运的是,C ++允许通过前向声明类来获得不完整的类型。 That means, following way-way, you can achieve the goal you want. 这意味着,按照方式,您可以实现您想要的目标。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM