有没有一种方法可以使类递归? [英] Is there a way to make a class recursive?

查看:86
本文介绍了有没有一种方法可以使类递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想创建一个类,该类可以具有本身是类型的对象。
像这样:

So I would like to create a class that can have an object which type is itself. Something like this:

class foo {

    foo Avalue = foo();
    foo Bvalue = foo();

    foo(int a, int b) {
        Avalue = goo(a);
        Bvalue = goo(b);
    }

    foo(foo a, int b) {
        Avalue = foo(a);
        Bvalue = goo(b);
    }

    foo(foo a, foo b) {
        Avalue = foo(a);
        Bvalue = foo(b);
    }
}

class goo : foo {

    int value;
}

这样我可以拥有一个总是以 goo对象终止的递归对象。
有办法吗?

so that I can have a recursive object that always terminates at "goo" objects. Is there a way to make it?

推荐答案

否。从根本上讲这是不可能的。想一想:该类将具有无限的大小(嗯,除非我没有其他成员,否则它将做什么?),并且没有可证明的定义/身份。

No. That is fundamentally impossible. Think about it: the class would have infinite size (well, unless it has no other members, I suppose, but then what does it do?), and no provable definition/identity.

不过,您可以存储指向其他 foo 对象的指针。只要不是每个 foo 都有一个成员指针,该成员指针指向另一个 foo ,或者如果引用形成循环依赖关系。无论哪种方式,编译器都不会以尝试的解决方案所必须的方式进行诊断,但是如果您不小心,则会在运行时发现问题。

You can store pointers to other foo objects, though. This works as long as not every foo has a member pointer that does point to another foo, or if the references form a cyclic dependency. Either way the compiler won't be diagnosing this in the way that it must with your attempted solution, but you can find trouble at runtime if you're not careful.

您的代码表明您正在实现一棵树。这就是(通常是一棵树) std :: map 的原因(我想是其中的几个),它是动态创建其节点并将其与指针链接的原因。就像每个链表的实现一样。

Your code suggests you're implementing a tree. This is the reason (well, one among a few, I suppose) that std::map, which is usually a tree, creates its nodes dynamically and links them with pointers. As does every linked list implementation.

这篇关于有没有一种方法可以使类递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆