c++ - 初始化在同一头文件中定义的底层的顶层类
问题描述
可能是个愚蠢的问题。我很抱歉,但我想做以下事情,
connectionState currentState;
class connectionState {
public:
.......
.......
};
相当
class connectionState {
public:
.......
.......
};
connectionState currentState;
前者根本不编译,而后者则编译。那么,没有办法做到这一点吗?
解决方案
对此有前向声明。前向声明也解决了循环依赖的问题:
class connectionState; // forward class declaration
extern connectionState currentState; // forward global extern variable declaration, now possible because connectionState is declared as a typename/class name
static connectionState currentState; // forward global static variable declaration
class connectionState { ... }; // implementation/definition, can access currentState
connectionState currentState = ...; // definition/initialization
connectionState currentState {...}; // definition/initialization
推荐阅读
- javascript - 使用 Ajax Timer 每秒在 ASP.net 的头部创建 Javascript 会导致问题
- python - 尝试使用标签从网站获取图像
- javascript - 我不断收到错误“main.js:19 Uncaught TypeError: firebase.database is not a function”
- qt - 如何使 QScrollArea 中 QStackedWidget 的小部件自动调整大小?
- angular - 当任何给定的 observables 发出值时,如何运行 tap 运算符?
- jenkins - Jenkins Pipeline - remoteTriggerJob 始终将状态返回为 Queued 尽管远程作业正在运行和完成
- angular - 在输入中仅显示对象名称 | FormControlName - 角
- android - 使用 OpenGLES 绘制圆形笔划
- neo4j - 如何在单个查询中更新一组节点上的序数属性?
- javascript - 关闭服务器后,Node-Cron 如何跟踪时间?