C++如何创建嵌套类来转发您的方法?
所以我的想法很简单 - 拥有一个可以拥有自己的公共方法的类和一个仅支持其中一些公共方法(伪代码)的嵌套类:
class API
{
public:
go();
stop();
friend class B
{
public:
void public_request()
{
request();
}
void public_go()
{
go()
}
};
private:
void request(){}
};
是否可以在 C++ 中实现这样的嵌套类以及如何实现?
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 such nested class in C++ and how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以用 C++ 创建本地类。局部类是在函数内部定义的类。
但这样的类有几个限制。了解它
不过,您无法像 Java 一样在 C++ 中创建嵌套类。嵌套类是另一个类范围内的类。
嵌套类的名称是其封闭类的本地名称(在封闭类的范围之外不可见)。除非使用显式指针或引用,否则嵌套类中的声明只能使用可见构造,包括封闭类中的类型名称、静态成员和枚举器 对于嵌套类,
需要注意的两个要点是:
因此,您需要使用组合或显式地将外部类对象的指针或引用传递给嵌套类
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:
So You will need to use composition or explicitly pass a pointer or reference of object of outer class to the nested class
是的,但是当您创建内部类时,您必须提供外部类的实例...这两种类型[大部分]是独立的,因此
B
不与任何特定的API
。更多伪代码
或者,您可以将
API
的实例传递给B
的函数 [B::go(API&)
] ,
API
不包含B
的实例,除非您显式添加实例。另请注意,
B
不需要通过API
授予友谊。作为内部类,B
已经可以访问API
的私有/受保护成员。然而,反之则不然...API
无法访问B
的私有/受保护成员,除非B
授予其权限。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 ofAPI
.More pseudo-code
Alternatively, you can pass an instance of
API
toB
's function [B::go(API&)
]Further,
API
does not contain an instance ofB
unless you explicitely add an instance.Also, note that
B
does not need to be granted friendship byAPI
. As an inner class,B
can already accessAPI
s private/protected members. The converse is not true, however...API
can not accessB
s private/protected members unlessB
grants it permission.不是直接的,至少不是像Java中那样。您的嵌套类必须包含对“外部”类的指针或引用。
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.