c++ - 如何在类中声明和初始化静态成员?
问题描述
当我编译包含以下头文件的代码时,我收到一条错误消息:
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 */
解决方案
最简单的做法是遵循错误消息的建议。如果它抱怨非常量静态,请将其设为 const。
static int const maxNumberOfNeighbors = 4;
尤其是考虑到它应该是一个常数,正如它的名字一样。你不会改变最大值吧!?
否则,如果您打算对其进行变异,只需在类定义之外初始化和定义它。
// At namespace scope, in one file
int Graph::Node::maxNumberOfNeighbors = 4;
推荐阅读
- python-3.x - YouCompleteMe 不可用:需要使用 Python (3.6.0+) 支持编译的 Vim
- aws-lambda - 具有 lambda-proxy 集成和 API 模型验证的无服务器框架
- python - 在 Matplotlib 中管理同一子图上多行的刻度
- android - audioplayers 包不能在三星手机(A8 和其他一些)上播放音频,但适用于模拟器和其他品牌手机
- api - 需要 Workday REST API 端点帮助
- python - 查找列名并在整个列值中保留某些字符串
- html - Shrinking div's background color with CSS
- postgresql - 易碎测试查询
- r - R:不能将“闭包”类型强制为“双”类型的向量(时间序列预测)
- javascript - 使用 fetch() 登录后如何重定向用户