Is there a way in C++ to render a class' interface private to all classes except a few?
I am writing a B-link tree and its attendant sub classes like a data page class and a node class etc.
I was wondering is there a way to protect the public interfaces of the nodes and pages such that only the b-link tree class itself can access them, WITHOUT simultaneously exposing the private methods of the pages and nodes to the b-link class开发者_如何学JAVA?
IE I have already thought of simply changing the 'public' interface of the pages and nodes into the protected category and then declaring the B-link tree as a friend but that gives the b-link tree access to private methods that I want to stay private.
Off the top of my head, you could do something like:
class FooAdapter;
class Foo
{
private:
void funcToExpose();
void funcToHide();
friend FooAdapter;
};
class FooAdapter
{
private:
Foo foo;
void funcToExpose() { foo.funcToExpose(); }
friend SomeFriend;
};
(Not compiled or tested, but you should get the idea.)
You can try defining your attendant sub classes in an anonymous namespace in the same translation unit as the b-tree. Supposedly that will make those clases inaccesible from outside that translation unit.
See Unnamed/anonymous namespaces vs. static functions
If you don't want the interfaces of the nodes and pages to be exposed in your API then just declare them inside your b-link implementation file. If the b-link implementation spans more than one file, then put the node and page class declarations in an implementation-only header file (co-located with your implementation files, not with your API headers).
精彩评论