简体   繁体   中英

Friend protected method in c++

I've got a class Foo that must be accessed "directly" in other class Bar. I'd like to build a little framework declaring the method of Bar (which is the friend method of Foo) protected. In this way I could build several classes children of Bar.

Gcc complains about that and it works only if the method is public.

How can I do? Example of my code:

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

Gcc message:

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);
                                           ^

Well, it should be obvious that you can't access protected/private members of a class from another class. This is also true if you try to friend the protected/private member function. So, you can't do this unless you put the method in a public section or make Foo a friend of Bar .

You can also do this by making the entire class Bar a friend of Foo . So either do this:

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

Or this:

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

If you want to make it so that Foo is only accessible by a single non-public method without complete access to Bar , you can create an intermediate class for that task.

class Foo;
class Bar;
class FooBar {
    friend Foo;
    friend Bar;
    Bar &bar_;
    FooBar (Bar &b) : bar_(b) {}
    float* internal(Foo &f);
};

class Foo {
    private:
        //some data
    public:
        //some methods
        friend float* FooBar::internal(Foo& f);
};

And now, Bar can call into this intermediate class in its own protected version of that method.

class Bar {
    friend FooBar;
    // some private data
    protected:
        float* internal(Foo& f) {
            FooBar fb(*this);
            return fb.internal(f);
        }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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