【发布时间】:2019-05-13 08:00:39
【问题描述】:
当我编译包含以下头文件的代码时,我收到一条错误消息:
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++17可以在类体中内联定义静态成员:
static inline int maxNumberOfNeighbors = 4;否则,必须先在类体中声明,再在外定义。 -
处理
static成员变量的“经典”方式是只在类中声明它们,然后进行定义和(可能)在外部初始化(在单个源文件中)。
标签: c++ initialization static-members