c++ - 是否可以动态初始化静态成员数组

标签 c++ static-members

关于在 C++ 中初始化静态成员的问题太多了,但我找不到这个。

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

这似乎可行,但我还想将 BAD_NODE 添加到此数组作为第一个元素。

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

以上代码无法编译。消息是

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

这是一个学校项目,我们在这个项目中使用数组实现链表。

最佳答案

如果你只有一个静态数据对象,但你想动态初始化它,你可能想在这里做的是创建一个单例对象作为你的 Node 的包装器类(class)。基本上,单例发生的事情是您创建一个类的单一版本,该类使用普通类构造函数初始化,但是构造函数、operator=() 和复制构造函数被声明为 private 。然后通过静态变量创建该类的单个静态版本,并且有一个公共(public)访问器方法允许您的代码的其他部分访问单例类(即,访问器返回对静态类的引用或常量引用你创造了)。

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_S 接口(interface)中添加使用 Node 类型所需的任何其他方法。所以一些常见的使用代码可能如下所示:

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

关于c++ - 是否可以动态初始化静态成员数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7451546/

相关文章:

c++ - 如何确定中间包含 "\0"的 std::string 的长度?

c++ - RVO 和返回 vector ,重用容量

c++ - 提高 C++ 中非常大常量的可读性

c++ - 静态无效函数链接错误

c++ - 为什么本地类中不允许使用静态数据成员?

python - Python 中如何检查静态变量是否存在?

c++ - 扩展枚举类

c++ - 如何将音频数据放入 AVFrame 进行编码

c++ - 如何在 C++ 中使用 snmpwalk

c++ - 静态成员错误地初始化为空字符串