相互递归类可能吗?
我阅读了如何使用前向声明来实现这一点。
class A
{
public:
B *objB;
void foo(){}
}
class B
{
public:
A *objA;
void foo(){}
}
只是想确认一下这种设计是否可行?
class A
{
public:
B objB;
void foo(){}
}
class B
{
public:
A objA;
void foo(){}
}
PS:如果有人也可以解释为什么/为什么不可以从类的角度解释为什么/为什么不可以,而不仅仅是从语言的角度,比如引用一些例子。这对于班级来说到底意味着什么?
I read how this can be made to work using forward declarations.
class A
{
public:
B *objB;
void foo(){}
}
class B
{
public:
A *objA;
void foo(){}
}
Just wanted to confirm if this design is ever possible ?
class A
{
public:
B objB;
void foo(){}
}
class B
{
public:
A objA;
void foo(){}
}
PS: If someone could also please explain why/why not this is possible logically in terms of classes, rather than just in terms of language, like by quoting some example. What exactly this signify in terms of classes ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第二个例子是不可能的。它表示为
A
分配的空间包含为B
分配的空间,而B
又包含为A
分配的空间,等等。这需要无限量的内存,并且需要无限量的时间来构建。The second example is not possible. It says that the space allocated for an
A
contains room for aB
, which in turn contains room for anA
, etc. This would require an infinite amount of memory, and would take an infinite amount of time to construct.不,无论是从语言上还是从班级上来说都不可能。
就类而言:每个 A 实例都包含一个 B 实例,B 实例又包含一个 A 实例... =>无限递归。这对于指针版本来说不是问题,因为指针可能不指向有效对象,或者所有 A 指针可能指向同一个对象等。
No, it is not possible either in terms of language or in terms of classes.
In terms of classes: Every A instance contains a B instance which contains an A instance which... => infinite recursion. This is not a problem with the pointer version because the pointer may not point to a valid object, or all A pointers may point to the same object, etc.
像你的第二个例子这样的相互递归类是不可能的。如果每个实例都有另一个类的对应实例,并且由于没有基本情况来停止递归,则类的大小将是无限的。显然,实例化这么大的类是很困难的。
Mutually recursive classes such as your second example are impossible. If each instance had a corresponding instance of the other class, and since there's no base case to stop th recursion, the size of the class would be infinite. Obviously it would be hard to instantiate such a large class.
3.9/5 告诉:
在第二个示例中,类 A 尝试定义类型不完整的成员变量,因此它的格式不正确。
3.9/5 tells :
In your second example, class A tries to define a member variable with incomplete type, hence it is an ill formed.