yar*_*oul 1 c++ initialization static-members
当我编译包含以下头文件的代码时,出现错误消息:
Graph.h:22: error: ISO C++ forbids in-class initialization of non-const
static member `maxNumberOfNeighbors'
Run Code Online (Sandbox Code Playgroud)
如何声明和初始化不是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 */
Run Code Online (Sandbox Code Playgroud)
最简单的操作是遵循错误消息的建议。如果它抱怨非常量静态变量,则使其为常量。
static int const maxNumberOfNeighbors = 4;
Run Code Online (Sandbox Code Playgroud)
特别是考虑到它应该是一个常量,无论其名称如何。您不会更改最大值,对!!
否则,如果您打算对其进行突变,请仅在类定义之外对其进行初始化和定义。
// At namespace scope, in one file
int Graph::Node::maxNumberOfNeighbors = 4;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |