Is there a way to make a class recursive?

两盒软妹~` 提交于 2019-12-30 14:54:30

问题


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;
}

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


回答1:


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.

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.

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.




回答2:


The problem with that is that the foo inside foo would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain a foo which would contain...



来源:https://stackoverflow.com/questions/54620646/is-there-a-way-to-make-a-class-recursive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!