So my Idea is simple - to have a class that can have its own public methosds and a nested class that would forvard only some of that public methods (pseudocode):
class API
{
public:
go();
stop();
friend class B
{
public:
void public_request()
{
request();
}
void public_go()
{
go()
}
};
private:
void request(){}
};
Is it possible to implement开发者_StackOverflow社区 such nested class in C++ and how?
It is possible to create a Local class in C++. Local class is a class defined inside an function.
But such an class has several restrictions. Read about it here in detail.
You cannot create Nested classes in C++ like Java though. Nested class is a class within the scope of another class.
The name of a nested class is local to its enclosing class(It is not visible outside the scope of the enclosing class). Unless you use explicit pointers or references, declarations in a nested class can only use visible constructs, including type names, static members, and enumerators from the enclosing class
Two important points to note with Nested classes are:
- Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes.
- Member functions of the enclosing class have no special access to members of a nested class.
So You will need to use composition or explicitly pass a pointer or reference of object of outer class to the nested class
Yes, but you have to provide an instance of the outer class when you create the inner one... the two types are [mostly] independant, so B
is not associated with any specific instance of API
.
More pseudo-code
struct API {
void go();
struct B {
B(API& api) : api(api) { }
void go() { api.go(); }
};
};
API a;
B b(a);
b.go();
Alternatively, you can pass an instance of API
to B
's function [B::go(API&)
]
struct API {
void go();
struct B {
void go(API& api) { api.go(); }
};
};
API a1, a2;
B b;
b.go(a1);
b.go(a2);
Further, API
does not contain an instance of B
unless you explicitely add an instance.
struct API {
struct B { };
B b;
};
Also, note that B
does not need to be granted friendship by API
. As an inner class, B
can already access API
s private/protected members. The converse is not true, however... API
can not access B
s private/protected members unless B
grants it permission.
Not directly, at least not in the same way as in Java. Your nested class has to contain a pointer or a reference to the "outer" class.
精彩评论