简体   繁体   中英

Linked-list with nested classes: how can I use nested class type before it is declared?

Ok, here's my problem, if a problem it is at all.

I'm building a linked list.
This linked list is composed of elements in form of a class.
Thus I have a class called, let's say, linked_list and a nested one called just node .

Obviously, the main class is meant for handling nodes and supply some functions to interact with them.

Here a draft of how it is supposed to look:

class linked_list
{
public:
    linked_list();
    ~linked_list();
    void setFirst(node *firstIn){first = firstIn;}
    node* getFirst(){return first};
    void forward();
    void forward(unsigned char);

private:
    node *first;
    node *current;

    class node
    {
    public:
        node();
        ~node();
        void function1();
        void function2();

    private:
        int various_data;
        node *next;
    };
};

Now, as you can imagine, the compiler gives me an error (two, actually) which tells me that the node type/class has not yet been declared, when I use it in the public section of the linked_list class to declare functions' arguments and return types.

I guess I could just invert public: and private: sections so that the declaration of the node class precedes its use, but this escamotage would annoy my (mild) OCD way too much for me to abide it.

Is there really no way other than inverting public: and private: ?
It kills me!

You can use a forward declaration for that.

#include ...

class node;

public class linked_list {
...
}

Note: This defeats the purpose of the inner class, because you are exposing it in your header. So, it is ok to do this for a simple exercise, but would be a bad architectural decision.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM