Is it possible to initialize a static array of elements dynamically

There are too many questions about initializing static members in C ++, and yet I could not find this one.

class Node {

  private:
    static const int INITIAL_SIZE = 100;
    static Node* node_space;
    static int OUT_OF_BOUNDS = 0;
    static Node BAD_NODE;

};

Node* Node::node_space = new Node[Node::INITIAL_SIZE];

This seems to work, but I also want to add BAD_NODE to this array as the first element.

Node Node::BAD_NODE = Node();
Node::node_space[OUT_OF_BOUNDS] = BAD_NODE;

The above does not compile. Message

Node.cpp:7: error: expected constructor, destructor, or type conversion before '=' token

This is for a school project in which we implement a linked list with an array.

+5
source share
2 answers

, , , Node. , singleton, , , operator=() copy-constructor private. , , singleton (.. Accessor ).

class Node_S
{
    private:

        //your original Node class we're wrapping in the singleton object
        struct Node {
            static const int INITIAL_SIZE = 100;
            static Node* node_space;
            static int OUT_OF_BOUNDS;
            static Node BAD_NODE;
        };

        //private default constructor is only called once
        Node_S()
        {
            //place your original initialization code for Node here
            Node::OUT_OF_BOUNDS = 0;
            Node::node_space = new Node[Node::INITIAL_SIZE];
            Node::BAD_NODE = Node();
            Node::node_space[Node::OUT_OF_BOUNDS] = Node::BAD_NODE;
        }

        //private copy and assignment operator
        Node_S(const Node_S&) {}
        Node_S& operator=(const Node_S&) { return *this; }

    public:

        static Node_S& get_instance() 
        {
            //here is where the single version of Node_S is created
            //at runtime
            static Node_S singleton_instance = Node_S();
            return singleton_instance;
        }

        //... Other public functions
};

Node_S::get_instance(). private, ... . , . , , Node get_instance(). singleton_instance - , , Node_S() , Node . , Node Node_S. , :

Node_S::Node a_node_copy = Node_S::get_instance().get_node(10);
+1

++ 11 (, ++ ":-)) :

Node* Node::node_space = new Node[Node::INITIAL_SIZE] { Node::BAD_NODE };

, first - . , , , OUT_OF_BOUNDS .

+1

All Articles