Is there a way to make a class recursive?

前端 未结 2 1878
挽巷
挽巷 2021-01-16 21:19

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 = fo         


        
相关标签:
2条回答
  • 2021-01-16 21:36

    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.

    0 讨论(0)
  • 2021-01-16 21:56

    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...

    0 讨论(0)
提交回复
热议问题