首页 > 解决方案 > 如何在类中声明和初始化静态成员?

问题描述

当我编译包含以下头文件的代码时,我收到一条错误消息:

Graph.h:22: error: ISO C++ forbids in-class initialization of non-const 
static member `maxNumberOfNeighbors'

如何声明和初始化非 const 的静态成员?

这是.h文件

#ifndef GRAPH_H
#define GRAPH_H

typedef char ElementType;
class Graph {
public:
    class Node {
    public:
        static int maxNumberOfNeighbors = 4;;
        int numberOfNeighbors;
        Node * neighbors;
        ElementType data;
        Node();
        Node(ElementType data);
        void addNeighbor(Node node);
    };

typedef Node* NodePtr;

Graph();
void addNode(Node node);
NodePtr getNeighbors(Node node);
bool hasCycle(Node parent);
private:
    NodePtr nodes;
    static int maxNumberOfNodes;
    int numberOfNodes;
};

#endif /* GRAPH_H */

标签: c++initializationstatic-members

解决方案


最简单的做法是遵循错误消息的建议。如果它抱怨非常量静态,请将其设为 const。

static int const maxNumberOfNeighbors = 4;

尤其是考虑到它应该是一个常数,正如它的名字一样。你不会改变最大值吧!?

否则,如果您打算对其进行变异,只需在类定义之外初始化和定义它。

// At namespace scope, in one file
int Graph::Node::maxNumberOfNeighbors = 4;

推荐阅读