C ++中受朋友保护的方法

gre*_*f82 2 c++ friend-function

我有一个Foo类,必须在其他类Bar中“直接”访问。我想构建一个小框架,声明Bar方法(这是Foo的朋友方法)受保护的方法。这样,我可以为Bar培养几个班级的孩子。

Gcc抱怨这一点,并且只有在该方法是公开的情况下才起作用。

我能怎么做?我的代码示例:

class Foo;
class Bar {
    protected:
        float* internal(Foo& f);
};
class Foo {
    private:
        //some data
    public:
        //some methods
        friend float* Bar::internal(Foo& f);
};
Run Code Online (Sandbox Code Playgroud)

Gcc讯息:

prog.cpp:4:16: error: ‘float* Bar::internal(Foo&)’ is protected
         float* internal(Foo& f);
                ^
prog.cpp:11:43: error: within this context
         friend float* Bar::internal(Foo& f);
                                           ^
Run Code Online (Sandbox Code Playgroud)

ras*_*ash 5

好吧,很明显,您不能从另一个类访问一个类的受保护/私有成员。如果您尝试与受保护的/私有成员函数成为朋友,也是如此。因此,除非您将该方法放在公共部分或与成为Foo朋友,否则您将无法执行此操作Bar

您也可以通过让整个班级Bar成为的朋友来做到这一点Foo。因此,要么这样做:

class Bar {
protected:
    friend class Foo; // Foo can now see the internals of Bar
    float* internal(Foo& f);
 };
class Foo {
private:
    //some data
public:
    //some methods
    friend float* Bar::internal(Foo& f);
};
Run Code Online (Sandbox Code Playgroud)

或这个:

class Bar {
protected:
    float* internal(Foo& f);
};
class Foo {
private:
    //some data
public:
    //some methods
    friend class Bar; // now Bar::internal has access to internals of Foo
};
Run Code Online (Sandbox Code Playgroud)