Can a Class be self-referenced?

2020-07-17 07:27发布

**If a structure can be a self-referential. like

struct list
{
     struct list *next;
};

as there is no difference between class and struct, except the default access specifiers. then is it possible to write a class...

class list
{
     class list *next;
};

or may be is there any different syntax to get a self-referential class.? if yes then how?**

标签: c++
1条回答
孤傲高冷的网名
2楼-- · 2020-07-17 07:39

Yes, but you can only self-reference a pointer or a reference to the class (or struct)

The typical way is just:

class list { list* next; }

If you need two classes to mutually refer to each other, you just need to forward declare the classes, like so:

class list;
class node;

class list { node* first; }
class node { list* parentList; node* next; }

When you don't have the full declaration (just a forward declaration), you can only declare pointers or references. This is because the compiler always knows the size of a pointer or reference, but doesn't know the size of the class or struct unless it has the full declaration.

查看更多
登录 后发表回答